如果我需要连接到网络服务并确保即使在屏幕旋转或电话突然弹出或活动已经放在后台后仍会继续下载,我还需采取什么方法?
我从这里的一些答案中读到,您可以使用AsyncTask或服务连接到Web服务。连接到Web服务时它真的是正确的方法吗?建议的方法和常用方法是什么?如果你能给我一些关于你建议的方法的解释和示例代码,我将不胜感激。
答案 0 :(得分:3)
这实际上取决于您的要求:
<强>服务强>
如果您的请求需要很长时间才能完成,并且您的应用程序在很大程度上取决于结果(持久性数据),我建议使用服务,因为android系统可以决定杀死被推送到后台的应用程序,您的请求将简直走了。
<强>的AsyncTask 强>
对于具有应用程序仅需要当前状态的数据的小请求(在实际应用程序关闭后可以丢弃的数据),我将使用AsyncTask。当方向发生变化时,这可能会变得非常棘手,因此我提供了一个示例( note - 这是获得想法的蓝图,而不是最终解决方案。)
我的应用程序和AsyncTask什么时候被杀?
当您将应用程序推送到后台时,它仍将处于活动状态。如果您使用antoher应用程序并且此请求更多内存,则android系统可以杀死您的活动应用程序以释放所需资源。从这一刻起,您的活动和任务就消失了。但是仍然有可能完成任务并将其结果保存在数据库或SD卡上。
public class YourActivity extends Activity {
private MyReqeustTask mRequestTask;
public void onCreate(Bundle state) {
// your activity setup
// get your running task after orientation change
mRequestTask = (MyRequestTask) getLastNonConfigurationInstance();
if (mRequestTask != null) {
mRequestTask.mActivity = new WeakReference<MyActivity>(this);
processRequest();
}
}
// call that somewhere - decide what implementation pattern you choose
// if you need more than a single request - be inventive ;-)
public startRequest() {
mRequestTask = new MyRequestTask();
mRequestTask.mActivity = new WeakReference<MyActivity>(this);
mRequestTaks.execute(your, params);
}
// this is a request to process the result form your actual request
// if it's still running, nothing happens
public processResult() {
if (mRequestTask == null || mRequest.getStatus() != Status.FINISHED) {
return;
}
Result result = mRequest.getResult();
// update and set whatever you want here
mRequestTask = null;
}
public Object onRetainNonConfigurationInstance() {
// retain task to get it back after orientation change
return mRequestTask;
}
private static MyRequestTaks extends AsyncTask<Params, Progress, Result> {
WeakReference<MyActivity> mActivity;
protected Result doInBackground(Params... params) {
// do your request here
// don't ever youe mActivity in here, publish updates instead!
// return your final result at the end
}
protected void onProgressUpdate(Progress... progress) {
MyActivity activity = mActivity.get();
if (activity != null) {
// do whatever your want to inform activity about undates
}
}
protected void onPostExecute(Result result) {
MyActivity activity = mActivity.get();
if (activity != null) {
// this will update your activity even if it is paused
activity.processRequest();
}
}
}
}