服务广播公司/ Runnable不会停止
问题描述:
我有一个广播公司的Foregound服务。服务广播公司/ Runnable不会停止
@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
}
};
正如你所看到的,我已经尝试了所有我能想到的停止命令。我在这里做错了什么?如何停止广播/可运行?
答
由于您的应用程序进程仍在运行,您的广播服务器会继续运行,因此您的线程将继续执行,除非您告诉它不要。
可以很容易地阻止你的线程,运行中的方法:
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;
}
谢谢你,你真棒! – aelveborn 2012-08-10 02:14:37