0

I am making AsynkTask within Service like this

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

}

when I am running the application it starting to print "taskDummy" every two second as expected, when I close application by prssing Back buttin still log printing continue as expected, but when I removed application from recent apps stack it stopped printing this should not happen I want my asynch task continue in this situation. even I can see my service is running from setting. please advise me.

Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113

2 Answers2

0

It's a known bug: swiping the service out from recent apps destroys it.
Try following solution.

Community
  • 1
  • 1
A.Vynohradov
  • 276
  • 1
  • 8
0

You need to explicitly call of asyncTaskObject.cancel(true); in onDestroy of your Activity(Or your event whenever you want.)

And then rewrite your while loop logic , something like that:

 // 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;
}
Lavekush Agrawal
  • 6,040
  • 7
  • 52
  • 85