我有一个广播公司的Foregound服务。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Service
Log.d("Service","Service started");
startTime = intent.getLongExtra("STARTTIME", 0);
endTime = intent.getLongExtra("ENDTIME", 0);
isRunning = true;
postNotification();
// Broadcaster
handler.removeCallbacks(updateRunnable);
handler.postDelayed(updateRunnable, DELAY);
return START_STICKY;
}
当我尝试停止服务时onDestroy()
运行并且一切正常,但updateRunnable
继续进行,因此仍然会进行广播。
private Runnable updateRunnable = new Runnable() {
public void run() {
Log.d("Service", "run");
currentTime = System.currentTimeMillis();
if(endTime > 0 && (currentTime-startTime) >= endTime) {
isRunning = false;
// Alarm
AlarmNotification alarmNotification = new AlarmNotification(context);
alarmNotification.startAlarm();
// Notification
AppNotification notify = new AppNotification(context);
notify.stopNotification();
update();
// Tried them all:
stopService(intentBroadcaster);
stopForeground(true);
stopSelf();
} else {
update();
}
handler.postDelayed(this, 1000); // 1 seconds
}
};
正如你所看到的,我已经尝试过我能想到的每一个停止命令。我在这做错了什么?如何停止广播/可运行?
答案 0 :(得分:0)
您的广播公司一直在运行,因为您的应用程序进程仍在运行,因此您的线程将继续执行,除非您告诉它不要。
在run方法中很容易停止你的线程:
private boolean shouldContinue = true;
private Runnable updateRunnable = new Runnable() {
public void run(){
// ... whaterver your doing
if(shouldContinue){
handler.postDelayed(this, 1000);
}
}
};
public void onDestroy(){
shouldContinue = false;
}