当我按下停止按钮通知我服务已停止但实际上它仍在后台工作我在我的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
冉冉说
开心每一天1111
拉风的咖菲猫
随时随地看视频慕课网APP
相关分类