【问题标题】:stop asynctask. How turn off or stop background process of another execution?停止异步任务。如何关闭或停止另一个执行的后台进程?
【发布时间】:2013-05-24 09:15:18
【问题描述】:

我正在创建一个 APK,但我遇到了问题。 我的 APK 完成后会发送一个 GET 请求。 我有一个 asynctask 类用于定期发送 GET 请求。 问题是当我再次启动应用程序时,我需要终止前一次启动的后台进程。 我把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

【问题讨论】:

    标签: android background android-asynctask


    【解决方案1】:

    问题是当我再次启动应用程序时需要杀死后台先前启动的进程。

    没有“先前启动的后台进程”,除非您在清单中做了一些非常不寻常的事情。大多数 Android 应用程序只有一个进程,因此如果您的 AsyncTask 正在执行某项操作,那么它正在您当前的进程中执行此操作。

    如何在下次执行 apk 时取消 Get_Backgnd 的执行?

    AsyncTask 对象上调用 cancel()。如果它正在运行,则该对象存在,因此在其上调用cancel()

    当然,正确的答案也可能是使用不涉及AsyncTask 的其他方法(例如AlarmManagerIntentService)重写您的应用程序以“定期发送Get 请求”。

    【讨论】:

    • 这个解决方案不能解决问题。如果我把cancel()放在上面,我就不能启动新的asyncTask。 apk 不发送新的 GET 请求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 2011-07-22
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多