如何以编程方式强制停止android服务[复制]

问题描述 投票:-3回答:2

我按下拖动按钮一个开始服务和其他停止它当我按下停止按钮通知我服务停止但实际上它仍然在后台工作我使用我的onStartCommand()方法中的计时器重复每一秒是它的原因..?以及如何立即强制停止服务。

public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(getApplicationContext(),"start..",Toast.LENGTH_SHORT).show();
    new Timer().scheduleAtFixedRate(new TimerTask() {

        private Handler handler = new Handler(){
            @Override
            public void dispatchMessage(Message msg) {
                Toast.makeText(getApplicationContext(),""+(counter+=1),Toast.LENGTH_SHORT).show();
            }
        };
        @Override
        public void run() {
            handler.sendEmptyMessage(0);
        }
    },0,1000);


    return START_STICKY;
}

`

和我的按钮动作: -

public void btnStart(View view){

    startService(new Intent(MainActivity.this,MyService.class));

}
public void btnStop(View view){

   stopService(new Intent(MainActivity.this,MyService.class));
}

我找到答案..!答案是必须在onDestroy方法中取消timer和timerTask

java android android-service
2个回答
0
投票

以下是如何停止服务的简化说明:

stopSelf()用于始终停止当前服务。

stopSelf(int startId)也用于停止当前服务,但仅当startId是上次启动服务时指定的ID时。

stopService(Intent service)用于停止服务,但从服务外部停止。

访问此link了解更多详情

请更换

return START_STICKY;

通过

return START_NOT_STICKY;

区别:

START_STICKY

系统将在它被杀死后尝试重新创建您的服务

START_NOT_STICKY

系统在杀死后不会尝试重新创建服务


0
投票

如果你打算停止服务,你应该调用stopService(Intent)ex:

Intent intent = new Intent(MainActivity.this, YourService.class);
stopService(intent);
© www.soinside.com 2019 - 2024. All rights reserved.