【问题标题】:Can I restart service completely fresh in android?我可以在android中完全重新启动服务吗?
【发布时间】:2016-06-19 00:46:18
【问题描述】:

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

}

我的活动代码是我如何重新启动服务

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-asynctask android-service


    【解决方案1】:

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

    【讨论】:

    • 谢谢哥们。我不知道我是怎么错过的。
    • 你欢迎兄弟 :) 有时它也会发生在我身上
    【解决方案2】:

    你没有停止服务属性。我认为你可以在AndroidManifest.xml中注册一个广播来重启服务或销毁服务。

    【讨论】:

    • 谢谢你我没有停止异步这是一个问题
    【解决方案3】:

    服务是在后台运行以执行的组件 长时间运行的操作,无需与用户交互 即使应用程序被销毁,它也能正常工作。

    AsyncTask 允许正确且轻松地使用 UI 线程。这节课 允许执行后台操作并在 UI 上发布结果 线程,而无需操作线程和/或处理程序。

    所以您不能停止您的 服务,因为您的 AsyncTask 继续运行。

    【讨论】:

      猜你喜欢
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多