android asynctask 全局变量,Android如何在onDestroy()之后重新连接到AsyncTask并重新启动onCreate()?...

我希望我有这个权利,因为它来自我不再使用的一些旧代码(我现在使用IntentService来做以往的事情).

这是我在主Activity中下载文件时最初的内容…

public class MyMainActivity extends Activity {

FileDownloader fdl = null;

...

// This is an inner class of my main Activity

private class FileDownloader extends AsyncTask {

private MyMainActivity parentActivity = null;

protected void setParentActivity(MyMainActivity parentActivity) {

this.parentActivity = parentActivity;

}

public FileDownloader(MyMainActivity parentActivity) {

this.parentActivity = parentActivity;

}

// Rest of normal AsyncTask methods here

}

}

关键是使用onRetainNonConfigurationInstance()来“保存”AsyncTask.

Override

public Object onRetainNonConfigurationInstance() {

// If it exists then we MUST set the parent Activity to null

// before returning it as once the orientation re-creates the

// Activity, the original Context will be invalid

if (fdl != null)

fdl.setParentActivity(null);

return(fdl);

}

然后,我有一个名为doDownload()的方法,如果指示downloadComplete的布尔值为true,则从onResume()调用该方法.布尔值在FileDownloader的onPostExecute(…)方法中设置.

private void doDownload() {

// Retrieve the FileDownloader instance if previousy retained

fdl = (FileDownloader)getLastNonConfigurationInstance();

// If it's not null, set the Context to use for progress updates and

// to manipulate any UI elements in onPostExecute(...)

if (fdl != null)

fdl.setParentActivity(this);

else {

// If we got here fdl is null so an instance hasn't been retained

String[] downloadFileList = this.getResources().getStringArray(R.array.full_download_file_list);

fdl = new FileDownloader(this);

fdl.execute(downloadFileList);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值