停止在内部使用处理程序的粘性服务

问题描述

我正在创建一项服务,该服务会持续显示烤面包片运行的时间。我想让它存在,甚至在应用程序被破坏后也是如此。 为了显示它运行了多长时间,我使用了一个处理程序。但是使用stopService()方法调用我无法停止它。另外,如果我在服务的onDestroy()上删除了回调,那么在显示第一个回调之后,它将停止显示烤面包。因此,我需要一种在不删除onDestroy()上的回调的情况下停止服务的方法,还是有其他方法可以继续显示吐司消息?

以下是与活动相关的代码:

Intent intent;

protected void onCreate(Bundle savedInstanceState) {    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_status);

    intent = new Intent(getApplicationContext(),MyService.class);

//OnButton.setOnclickListener() - > StartLogging();
//StopButton.setOnclickListener() - > StopLogging();

}

private void StartLogging() {
    startService(intent);
}

void stopLogging() {
    stopService(intent);
}

服务中:

    public MyService() {
    }

    Handler handler;
    Runnable r;
    static int i;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId) {
        handler = new Handler();
        onTaskRemoved(intent);
        stopSelf();
        Toast.makeText(getApplicationContext(),"This is a Service running in Background",Toast.LENGTH_SHORT).show();
        startLogging();
        return START_STICKY; // I tried return START_NOT_STICKY; as well but the service is not stopping on button click/handler keeps posting message if not removed callbacks from onDestroy(),but if did then it shows toasts once.
    }

    private void startLogging() {

        r = new Runnable() {
            public void run() {

                i++;

                Toast.makeText(getApplicationContext(),"running in Background for  "+(i*5),Toast.LENGTH_SHORT).show();

                handler.postDelayed(this,5000);
            }
        };

        handler.postDelayed(r,5000);
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
         
        Toast.makeText(getApplicationContext(),"It is removed.",Toast.LENGTH_SHORT).show();

        super.onTaskRemoved(rootIntent);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(getApplicationContext(),"It is destroyed.",Toast.LENGTH_SHORT).show();
//        handler.removeCallbacks(r);

        super.onDestroy();
    }

}

使用stopService()呼叫后,它不会停止服务。 请建议我如何在按钮点击监听器stopLogging()方法下停止该服务,并在按按钮之前继续显示吐司?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...