2017-05-27 29 views
0

我有一个AsyncTask从url加载图像到imageView。 doInBackground()从url中加载图像,onPostExecute()中的方法将图像设置为imageView。如果用户在图像加载时最小化应用程序,AsyncTask的doInBackground()方法还没有完成,会发生什么?如何在应用程序最小化时处理Asyntask?

+0

它会下载但不设置它,做onResume来处理场景 –

+0

你可以看看这个链接https://stackoverflow.com/questions/31085406/what-happens-to-running-asynctasks-when-活动更改 –

+0

我不是说活动更改,用户只需在加载图像时按菜单按钮将其置于后台 – pvn

回答

0

asynctask将继续工作。回到UI线程时,您是否负责处理上下文的有效性?

所以,最好的解决方案是设置一个侦听器并取消它的销毁,验证它是否在onDestroy上存在。现在

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); 
} 

,在您的活动,呼吁的AsyncTask之前,请致电:

myAsyncTask.setOnProcessFinishedListener(new OnProcessFinishedListener {  
    void onProcessFishined(String result) { 
     textView.setText(result); 
    } 
}); 

而在你的onDestroy方法:

myAsyncTask.setOnProcessFinishedListener(null); 

还有其他的方法有点比使用更优雅一个AsyncTask(你尝试过Picasso或Glide的图像吗?),但这是一个Start。

+0

我知道AsyncTask将继续工作。我想要了解的是,如果我们的应用程序在后台,因为用户按下菜单按钮(活动未被破坏)图像是否会被设置?尽管我们的活动不在前台,UI界面线程是否可以将图像设置为imageview? – pvn

+0

只要ImageView存在并且可以访问,它就会 –

相关问题