android - 我可以在 android 中完全重新启动服务吗?

标签 android android-asynctask android-service

我正在通过其中的服务和异步任务运行后台任务。首先,它从数据库中获取所有数据并在用户更改某些选项时开始运行我销毁并再次启动服务以处理新数据但不幸的是服务从它停止的地方运行。所以我想开始全新的服务。我试过 START_NOT_STICKY 但没用。

public class MyService extends Service {
    public void onCreate(){
        super.onCreate();

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
       Bundle extras = intent.getExtras();
       process.execute();
       return START_NOT_STICKY;
    }
    public void onDestroy() {
       stopSelf();
       super.onDestroy();
       Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
    class ProcessImageAsync extends AsyncTask<String, Integer, String> {  
        @Override
        protected String doInBackground(String... params) {
          // here im getting content from db and processing .
        if (isCancelled()) {
           System.exit(0);
        }
        }
    }

}

这里的 Activity 代码是我如何重启服务

public void startServiceFucntion(int type){

        if(isMyServiceRunning(MyService.class)){
            if (type == 1){
                Intent serviceIntent = new Intent(this, MyService.class);
                stopService(serviceIntent);
                startServiceFucntion(0);
            }
        } else {
            Intent serviceIntent = new Intent(this, MyService.class);
            if(serviceReceiver == null){
                registerReceiver(serviceReceiver, intentSFilter);
            }
            startService(serviceIntent);
        }
}

最佳答案

我认为您没有正确停止服务,您的异步任务继续在后台运行。您还需要在销毁服务时取消异步任务。

关于android - 我可以在 android 中完全重新启动服务吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35810347/

相关文章:

android - 房间 : Proper way to test DAO Apis

android - 如何在软键盘 Android 的前面显示我的布局?

android - 如何在选项卡式基本应用程序中制作像 skype 一样的聊天窗口

android - 如何限制使用ASyncTask启动的线程数量?

java - 在 AsyncTask 中添加 View ( TextView )

java - Android 应用程序使用 AsyncTask 下载文件时出现内存泄漏

android - 重新打开 Activity 时 AsyncTask(doInBackground 方法)出现问题

android - 如何使用 Work Manager 处理来自 FusedLocationProviderClient 的位置更新?

android - 当 IntentService 启动时,Application 对象会启动吗?

android - 当应用程序处于后台时收听