我在这样的Service
内制作AsynkTask
public class MyService extends Service {
private final IBinder mBinder = new LocalBinder();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("log_tag", "Service started");
ReceiveAsyncTask receiveATask = new ReceiveAsyncTask();
receiveATask.execute();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
Log.v("log_tag", "onBind");
return mBinder;
}
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
class ReceiveAsyncTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
taskDummy();
return null;
}
@Override
protected void onPreExecute() {
Log.v("log_tag", "onPreExecute");
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
Log.v("log_tag", "onPostExecute");
super.onPostExecute(result);
}
@Override
protected void onCancelled() {
Log.v("log_tag", "onPostExecute");
super.onCancelled();
}
}
private void taskDummy() {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("log_tag", "taskDummy");
}
}
/** method for clients */
public int getRandomNumber() {
Log.v("log_tag", "inner Method called");
return 100;
}
}
当我运行应用程序时,它开始按预期每隔两秒打印一次“taskDummy”,当我通过prssing Back buttin
关闭应用程序仍然按预期继续日志打印,但是当我从最近的应用程序堆栈中删除应用程序时停止打印这不应该发生我希望我的asynch任务继续在这种情况下。即使我可以看到我的服务正在从设置运行。请告诉我。
答案 0 :(得分:0)
这是一个众所周知的错误:从最近的应用程序中刷出服务会破坏它。
请尝试关注solution。
答案 1 :(得分:0)
您需要在活动asyncTaskObject.cancel(true);
中明确调用onDestroy
(或随时随地调用您的活动。)
然后重写你的while循环逻辑,类似的东西:
// Create this variable is Your Asyantask class.
private boolean isRunning = true;
@Override
protected void onCancelled() {
isRunning = false;
}
@Override
protected String doInBackground(Void... params) {
while (isRunning ) {
// Your processing
}
return null;
}