0

I am creating an APK but I have a problem. My APK sends a GET request when it finishes. I have a asynctask class for sending a GET request (GPS). The problem is that when I start the application again I need to kill the background processes of the previous launch. I put uses-permission android:name="android.permission.RESTART_PACKAGES" and uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" in the manifest.xml, and used the following code:

if (URLUtil.isValidUrl(URL_Pet_GET) && URLUtil.isValidUrl(URL_Host)){
    //Get_Backgnd.cancel(true); not working  
    context.getSystemService(Context.ACTIVITY_SERVICE);
    manager.killBackgroundProcesses(String.valueOf(process.processName));
    //not working

    //ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
    //activityManager.restartPackage(packageName);
    //not working

    pet_get_backgrnd Get_Backgnd = new pet_get_backgrnd();
    Get_Backgnd.execute();  //Send GET request that I need stop on next execution of apk 
}  
private class pet_get_backgrnd extends AsyncTask<Context, Object, Object>{
    /*@Override
    protected void onPreExecute() {
        cancel(true);
    }*/ //not working

    @Override
    protected Object doInBackground(Context... params) { 
      //send Get requests
    }
}

How can I cancel the execution of Get_Backgnd on the next execution of the APK? or same How can I cancel the execution of Get_Backgnd of the previous execution of the APK?

Thanks

Ry-
  • 218,210
  • 55
  • 464
  • 476

1 Answers1

0

The cancel() method on AsyncTask does not actually cancel execution but rather sets a flag that can be viewed by using the isCancelled() method. You'll need to manually check that flag in doInBackground() and write how you'd like your Task to handle the cancel. See this answer for an example of this and some useful links on canceling AsyncTasks.

In order to ensure that your AsyncTask doesn't persist, you can place the call to cancel in onPause() or onDestroy() of the Activity that spawns it, whichever you think is more appropriate, so that the Task is killed once it's no longer relevant. It's important that this is done in the Activity that actually creates the task, you won't be able to cancel the task on subsequent runs of the APK because you no longer have a reference to it. That, coupled with the manual checking of isCancelled() should help give you the behavior your require.

Community
  • 1
  • 1
MattDavis
  • 5,158
  • 2
  • 23
  • 35