【问题标题】:cancel() not working, and killBackgroundProcesses neithercancel() 不起作用,并且 killBackgroundProcesses 也没有
【发布时间】:2013-05-20 10:33:57
【问题描述】:

我正在创建一个 APK,但我遇到了问题。我的 APK 完成后会发送一个 GET 请求。我有一个用于发送 GET 请求(GPS)的 asynctask 类。问题是当我再次启动应用程序时,我需要终止前一次启动的后台进程。我将uses-permission android:name="android.permission.RESTART_PACKAGES" 和uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" 放在manifest.xml 中,并使用了以下代码:

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

如何在下次执行 APK 时取消执行 Get_Backgnd?或相同 如何取消之前执行APK的Get_Backgnd执行?

谢谢

【问题讨论】:

    标签: android android-asynctask kill


    【解决方案1】:

    AsyncTask 上的cancel() 方法实际上并没有取消执行,而是设置了一个可以使用isCancelled() 方法查看的标志。您需要在doInBackground() 中手动检查该标志,并写下您希望您的任务如何处理取消。 See this answer for an example of this and some useful links on canceling AsyncTasks.

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      相关资源
      最近更新 更多