Android 当应用程序最小化时,如何处理Asyntask?
我有一个异步任务,用于将图像从url加载到imageView。doInBackground()从url加载图像,onPostExecute()中的方法将图像设置到imageView中。如果用户在加载图像时最小化应用程序,即AsyncTask的doInBackground()方法尚未完成,会发生什么情况?AsyncTask将继续工作。是您在返回UI线程时处理上下文有效性的责任 所以,最好的解决方案是设置一个侦听器并在destroy上取消设置它,验证它在onDestroy上的存在性Android 当应用程序最小化时,如何处理Asyntask?,android,android-asynctask,Android,Android Asynctask,我有一个异步任务,用于将图像从url加载到imageView。doInBackground()从url加载图像,onPostExecute()中的方法将图像设置到imageView中。如果用户在加载图像时最小化应用程序,即AsyncTask的doInBackground()方法尚未完成,会发生什么情况?AsyncTask将继续工作。是您在返回UI线程时处理上下文有效性的责任 所以,最好的解决方案是设置一个侦听器并在destroy上取消设置它,验证它在onDestroy上的存在性 private
private class MyAsyncTask extends AsyncTask<String, String, String> {
private OnProcessFinishedListener listener;
public void setOnProcessFinishedListener(OnProcessFinishedListener listener) {
this.listener = listener;
}
@Override
protected String doInBackground(String... urls) {
///Your request some info and return it. This case, a String, but could be anything.
}
@Override
protected void onPostExecute(String result) {
if(listener != null) {
listener.onProcessFinished(result);
}
}
}
public interface OnProcessFinishedListener {
void onProcessFishined(String result);
}
在onDestroy方法中:
myAsyncTask.setOnProcessFinishedListener(null);
还有比使用异步任务更优雅的其他方法(你有没有尝试过毕加索或Glide的图像?),但这是一个开始。它将下载但不设置,在onResume中执行操作以处理场景你可以查看此链接我不是说活动更改,当图像加载时,用户只需按“菜单”按钮将其置于后台,我就知道该任务将继续工作。我想了解的是,如果我们的应用程序在后台,因为用户按下菜单按钮(活动未被破坏),图像会被设置吗?尽管我们的活动不在前台,UI线程是否可以将图像设置为imageview?只要imageview存在并且可以访问,它就会
myAsyncTask.setOnProcessFinishedListener(null);