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

4

1 回答 1

0

AsyncTask 上的cancel()方法实际上并没有取消执行,而是设置了一个可以使用该isCancelled()方法查看的标志。您需要手动检查该标志doInBackground()并写下您希望您的任务如何处理取消。有关此示例的示例以及有关取消 AsyncTasks 的一些有用链接,请参见此答案。

为了确保您的 AsyncTask 不会持续存在,您可以在产生它的 Activity 中调用取消调用,onPause()无论onDestroy()您认为哪个更合适,这样一旦不再相关,Task 就会被终止。重要的是,这在实际创建任务的 Activity 中完成,您将无法在 APK 的后续运行中取消任务,因为您不再拥有对它的引用。再加上手动检查isCancelled()应该有助于为您提供所需的行为。

于 2013-05-24T19:00:29.930 回答