这是库中downloadRequestqueue类的实现。此java文件在其add request函数中使用工作管理器,但未调用工作管理器getworkinfobyliveId函数。我认为问题是由于该java类的生命周期所有者我也已经在此类中实现
public class DownloadRequestQueue extends AppCompatActivity implements LifecycleOwner
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry=new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
}
@Override
public void onStart() {
super.onStart();
mLifecycleRegistry=new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
mLifecycleRegistry=new LifecycleRegistry(this);
Log.d("uu",mLifecycleRegistry+"");
return mLifecycleRegistry;
}
public DownloadRequestQueue(Context context) {
this.context = context;
currentRequestMap = new ConcurrentHashMap<>();
sequenceGenerator = new AtomicInteger();
}
public static void initialize(Context context) {
getInstance(context);
}
public static DownloadRequestQueue getInstance(Context context) {
if (instance == null) {
synchronized (DownloadRequestQueue.class) {
if (instance == null) {
instance = new DownloadRequestQueue(context);
}
}
}
return instance;
}
private int getSequenceNumber() {
return sequenceGenerator.incrementAndGet();
}
public void pause(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
request.setStatus(Status.PAUSED);
}
}
public void resume(int downloadId) {
final Response response = new Response();
final DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
request.setStatus(Status.QUEUED);
request.deliverStartEvent();
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
Log.d("fff",request.getOnProgressListener()+"");
String json = gson.toJson(request);
prefsEditor.putString("SerializableObject", json);
prefsEditor.commit();
Data data = new Data.Builder().putInt("ID", downloadId).build();
final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).setInputData(data).build();
WorkManager.getInstance().enqueue(workRequest);
WorkManager.getInstance().getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(@Nullable WorkInfo workInfo) {
if (workInfo != null) {
Log.d("this","dip");
if (workInfo.getState().isFinished()) {
Data data = workInfo.getOutputData();
String output = data.getString("Response");
if (output.equals(Status.CANCELLED + "")) {
response.setCancelled(true);
}
if (output.equals(Status.PAUSED + "")) {
response.setPaused(true);
}
if (output.equals("abc")) {
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(new Exception());
response.setError(error);
}
if (output.equals("def")) {
Error error = new Error();
error.setServerError(true);
response.setError(error);
}
}
if (response.isSuccessful()) {
request.deliverSuccess();
} else if (response.isPaused()) {
request.deliverPauseEvent();
} else if (response.getError() != null) {
request.deliverError(response.getError());
} else if (!response.isCancelled()) {
request.deliverError(new Error());
}
}
}
});
// request.setFuture(Core.getInstance()
// .getExecutorSupplier()
// .forDownloadTasks()
// .submit(new DownloadRunnable(request)));
}
}
private void cancelAndRemoveFromMap(DownloadRequest request) {
if (request != null) {
request.cancel();
currentRequestMap.remove(request.getDownloadId());
}
}
public void cancel(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
cancelAndRemoveFromMap(request);
}
public void cancel(Object tag) {
for (Map.Entry<Integer, DownloadRequest> currentRequestMapEntry : currentRequestMap.entrySet()) {
DownloadRequest request = currentRequestMapEntry.getValue();
if (request.getTag() instanceof String && tag instanceof String) {
final String tempRequestTag = (String) request.getTag();
final String tempTag = (String) tag;
if (tempRequestTag.equals(tempTag)) {
cancelAndRemoveFromMap(request);
}
} else if (request.getTag().equals(tag)) {
cancelAndRemoveFromMap(request);
}
}
}
public void cancelAll() {
for (Map.Entry<Integer, DownloadRequest> currentRequestMapEntry : currentRequestMap.entrySet()) {
DownloadRequest request = currentRequestMapEntry.getValue();
cancelAndRemoveFromMap(request);
}
}
public Status getStatus(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
return request.getStatus();
}
return Status.UNKNOWN;
}
public void addRequest(final DownloadRequest request) {
Log.d("did", request.getUrl() + "");
final Response response = new Response();
Log.d("yoii", request.getOnProgressListener()+"");
request.setStatus(Status.QUEUED);
abc=request.getOnProgressListener()+"";
onProgressListener1=request.getOnProgressListener();
currentRequestMap.put(request.getDownloadId(), request);
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
Log.d("fff",request.getOnProgressListener()+"");
request.setOnProgressListener(request.getOnProgressListener());
String json = gson.toJson(request);
ArrayList<Integer> arrayList=new ArrayList<Integer>();
arrayList.add(1);
prefsEditor.putString("SerializableObject", json);
prefsEditor.commit();
if (request != null) {
Log.d("999", currentRequestMap.get(request.getDownloadId()).getUrl() + "");
}
if (request == null) {
Log.d("none", "bro");
}
if (request != null) {
Log.d("all", request.getUrl() + "");
}
if (request == null) {
Log.d("none", "bro");
}
Data data = new Data.Builder().putInt("ID", request.getDownloadId()).putString("status", request.getStatus() + "").build();
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).setInputData(data).build();
WorkManager.getInstance().enqueue(workRequest);
Log.d("boss", "pls");
WorkManager.getInstance().getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(@Nullable WorkInfo workInfo) {
Log.d("abd","see");
if(workInfo==null){
Log.d("bug","buggy");
}
if (workInfo != null) {
Log.d("boss2", "pls2");
if (workInfo.getState().isFinished()) {
Log.d("boss3", "pls3");
Data data = workInfo.getOutputData();
String output = data.getString("Response");
Log.d("boss4", output);
if (output.equals(Status.CANCELLED + "")) {
response.setCancelled(true);
}
if (output.equals(Status.PAUSED + "")) {
response.setPaused(true);
}
if (output.equals("succ")) {
response.setSuccessful(true);
}
if (output.equals("abc")) {
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(new Exception());
response.setError(error);
}
if (output.equals("def")) {
Error error = new Error();
error.setServerError(true);
response.setError(error);
}
}
if (response.isSuccessful()) {
request.deliverSuccess();
} else if (response.isPaused()) {
request.deliverPauseEvent();
} else if (response.getError() != null) {
request.deliverError(response.getError());
} else if (!response.isCancelled()) {
request.deliverError(new Error());
}
}
}
});
}
public void finish(DownloadRequest request) {
currentRequestMap.remove(request.getDownloadId());
}
}
public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
currentRequestMap=new ConcurrentHashMap<>();
mPrefs=PreferenceManager.getDefaultSharedPreferences(context);
}
@NonNull
@Override
public Result doWork() {
int a = getInputData().getInt("ID",2);
String statu = getInputData().getString("status");
Gson gson = new Gson();
String json = mPrefs.getString("SerializableObject", "");
if(json.equals("")){
Log.d("noii","nn");
}
request = gson.fromJson( json, DownloadRequest.class);
Log.d("zoiiii",currentRequestMap.get(a)+"")
if(request!=null){
Log.d("soii",request.getStatus()+"");
}
else{
Log.d("loii","toy");
}
Response response = new Response();
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
try {
Log.d("koko","gogo");
if(request.getOnProgressListener()==null){
Log.d("dope",request.getUrl()+"");
//progressHandler = new ProgressHandler(request.getOnProgressListener());
}
if (request.getOnProgressListener() != null) {
Log.d("toll","lol");
progressHandler = new ProgressHandler(request.getOnProgressListener());
}
Log.d("suppp","ppp");
tempPath = Utils.getTempPath(request.getDirPath(), request.getFileName());
File file = new File(tempPath);
DownloadModel model = getDownloadModelIfAlreadyPresentInDatabase();
Log.d("dupp","nupp");
if (model != null) {
Log.d("love","no");
if (file.exists()) {
request.setTotalBytes(model.getTotalBytes());
request.setDownloadedBytes(model.getDownloadedBytes());
} else {
removeNoMoreNeededModelFromDatabase();
request.setDownloadedBytes(0);
request.setTotalBytes(0);
model = null;
}
}
Log.d("ab","devel");
httpClient = ComponentHolder.getInstance().getHttpClient();
Log.d("ggs","iipu");
httpClient.connect(request);
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
httpClient = Utils.getRedirectedConnectionIfAny(httpClient, request);
responseCode = httpClient.getResponseCode();
eTag = httpClient.getResponseHeader(Constants.ETAG);
Log.d("sipi","kipi");
if (checkIfFreshStartRequiredAndStart(model)) {
model = null;
Log.d("lova","nova");
}
if (!isSuccessful()) {
Log.d("lvv","nppp");
Error error = new Error();
error.setServerError(true);
error.setServerErrorMessage(convertStreamToString(httpClient.getErrorStream()));
error.setHeaderFields(httpClient.getHeaderFields());
error.setResponseCode(responseCode);
response.setError(error);
Data output = new Data.Builder()
.putString("Response","abc")
.build();
return Result.failure(output);
}
setResumeSupportedOrNot();
Log.d("coder","npppp");
totalBytes = request.getTotalBytes();
if (!isResumeSupported) {
deleteTempFile();
}
if (totalBytes == 0) {
totalBytes = httpClient.getContentLength();
request.setTotalBytes(totalBytes);
}
if (isResumeSupported && model == null) {
createAndInsertNewModel();
}
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
Log.d("dodo","soso");
request.deliverStartEvent();
Log.d("coco","momo");
inputStream = httpClient.getInputStream();
byte[] buff = new byte[BUFFER_SIZE];
if (!file.exists()) {
if (file.getParentFile() != null && !file.getParentFile().exists()) {
if (file.getParentFile().mkdirs()) {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
} else {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
}
this.outputStream = FileDownloadRandomAccessFile.create(file);
if (isResumeSupported && request.getDownloadedBytes() != 0) {
outputStream.seek(request.getDownloadedBytes());
}
Log.d("miggy","siggy");
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
do {
Log.d("left","some");
final int byteCount = inputStream.read(buff, 0, BUFFER_SIZE);
if (byteCount == -1) {
break;
}
outputStream.write(buff, 0, byteCount);
request.setDownloadedBytes(request.getDownloadedBytes() + byteCount);
Log.d("now1","one1");
sendProgress();
Log.d("now2","one2");
syncIfRequired(outputStream);
Log.d("common","yessin");
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
sync(outputStream);
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
} while (true);
final String path = Utils.getPath(request.getDirPath(), request.getFileName());
Utils.renameFileName(tempPath, path);
response.setSuccessful(true);
Log.d("yup","dove");
if (isResumeSupported) {
removeNoMoreNeededModelFromDatabase();
}
} catch (IOException | IllegalAccessException e) {
if (!isResumeSupported) {
deleteTempFile();
}
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(e);
response.setError(error);
Data output = new Data.Builder()
.putString("Response","def")
.build();
return Result.failure(output);
} finally {
closeAllSafely(outputStream);
}
Log.d("final","done");
Data output = new Data.Builder()
.putString("Response","succ")
.build();
return Result.success(output);
}
private void deleteTempFile() {
File file = new File(tempPath);
if (file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
private boolean isSuccessful() {
return responseCode >= HttpURLConnection.HTTP_OK
&& responseCode < HttpURLConnection.HTTP_MULT_CHOICE;
}
private void setResumeSupportedOrNot() {
isResumeSupported = (responseCode == HttpURLConnection.HTTP_PARTIAL);
}
private boolean checkIfFreshStartRequiredAndStart(DownloadModel model) throws IOException,
IllegalAccessException {
if (responseCode == Constants.HTTP_RANGE_NOT_SATISFIABLE || isETagChanged(model)) {
if (model != null) {
removeNoMoreNeededModelFromDatabase();
}
deleteTempFile();
request.setDownloadedBytes(0);
request.setTotalBytes(0);
httpClient = ComponentHolder.getInstance().getHttpClient();
httpClient.connect(request);
httpClient = Utils.getRedirectedConnectionIfAny(httpClient, request);
responseCode = httpClient.getResponseCode();
return true;
}
return false;
}
private boolean isETagChanged(DownloadModel model) {
return !(eTag == null || model == null || model.getETag() == null)
&& !model.getETag().equals(eTag);
}
private DownloadModel getDownloadModelIfAlreadyPresentInDatabase() {
return ComponentHolder.getInstance().getDbHelper().find(request.getDownloadId());
}
private void createAndInsertNewModel() {
DownloadModel model = new DownloadModel();
model.setId(request.getDownloadId());
model.setUrl(request.getUrl());
model.setETag(eTag);
model.setDirPath(request.getDirPath());
model.setFileName(request.getFileName());
model.setDownloadedBytes(request.getDownloadedBytes());
model.setTotalBytes(totalBytes);
model.setLastModifiedAt(System.currentTimeMillis());
ComponentHolder.getInstance().getDbHelper().insert(model);
}
private void removeNoMoreNeededModelFromDatabase() {
ComponentHolder.getInstance().getDbHelper().remove(request.getDownloadId());
}
private void sendProgress() {
if (request.getStatus() != Status.CANCELLED) {
Log.d("ttyl","ggyl");
if (progressHandler != null) {
Log.d("mozz","illa");
progressHandler
.obtainMessage(Constants.UPDATE,
new Progress(request.getDownloadedBytes(),
totalBytes)).sendToTarget();
}
else{
Log.d("maybe","into");
}
}
}
private void syncIfRequired(FileDownloadOutputStream outputStream) {
final long currentBytes = request.getDownloadedBytes();
final long currentTime = System.currentTimeMillis();
final long bytesDelta = currentBytes - lastSyncBytes;
final long timeDelta = currentTime - lastSyncTime;
if (bytesDelta > MIN_BYTES_FOR_SYNC && timeDelta > TIME_GAP_FOR_SYNC) {
sync(outputStream);
lastSyncBytes = currentBytes;
lastSyncTime = currentTime;
}
}
private void sync(FileDownloadOutputStream outputStream) {
boolean success;
try {
outputStream.flushAndSync();
success = true;
} catch (IOException e) {
success = false;
e.printStackTrace();
}
if (success && isResumeSupported) {
ComponentHolder.getInstance().getDbHelper()
.updateProgress(request.getDownloadId(),
request.getDownloadedBytes(),
System.currentTimeMillis());
}
}
private void closeAllSafely(FileDownloadOutputStream outputStream) {
if (httpClient != null) {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
if (outputStream != null) {
try {
sync(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
if (outputStream != null)
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String convertStreamToString(InputStream stream) {
StringBuilder stringBuilder = new StringBuilder();
if (stream != null) {
String line;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(stream));
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException ignored) {
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (NullPointerException | IOException ignored) {
}
}
}
return stringBuilder.toString();
}