为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

冉冉说 2022-11-02 16:54:16
当我按下停止按钮通知我服务已停止但实际上它仍在后台工作我在我的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
查看完整描述

2 回答

?
开心每一天1111

TA贡献1836条经验 获得超13个赞

以下是如何停止服务的简化描述:

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

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

stopService(Intent service)是用来停止服务的,但是从外部服务被停止。

访问此链接了解更多详情

请更换

return START_STICKY;

经过

return START_NOT_STICKY;

区别:

START_STICKY

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

START_NOT_STICKY

系统被杀死后不会尝试重新创建您的服务


查看完整回答
反对 回复 2022-11-02
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

如果您打算停止您启动的服务,您应该调用 stopService(Intent) 例如:


Intent intent = new Intent(MainActivity.this, YourService.class);

stopService(intent);


查看完整回答
反对 回复 2022-11-02
  • 2 回答
  • 0 关注
  • 232 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号