朋友,錯誤線程已啓動/預定
我在我的應用程序中設置了一個AlarmManager。 AlarmManager計劃每xx啓動一次後臺服務,這裏是1分鐘。它的工作很好一段時間。但很可惜,我得到一個錯誤:thead已經開始/預定。 我有這樣的感覺,我可能不會使用正確的析構函數。 將不勝感激您的支持。
我的繼承人啓動該AlarmManager活動的代碼
PendingIntent pi;
AlarmManager mgr;
mgr=(AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(DataCollectionActivity.this, HUJIDataCollectionService.class);
pi = PendingIntent.getService(DataCollectionActivity.this, 0, i, 0);
........
if (viewId == R.id.b_startService) {
mgr.cancel(pi);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() , 1* 60* 1000, pi);}
........
if (viewId == R.id.b_stopService) {
mgr.cancel(pi);}
和我的繼承人服務的重要代碼:
private Runnable LocationUpdateTimerTask = new Runnable() {
public void run() {
Log.i(ctx.getString(R.string.app_name),
"HUJIDataCollectionService, 1 LocationUpdateTimerTask, start");
setuplistenerandrequestupdates();
mHandler.removeCallbacks(LocationUpdateTimerTask);
}
};
private Runnable SendDataStopLocationUpdatesTimerTask = new Runnable() {
public void run() {
sendDataToServer();
mHandler.removeCallbacks(SendDataStopLocationUpdatesTimerTask);
ServiceIntervalTimerTask.cancel();
Intent service = new Intent(ctx, HUJIDataCollectionService.class);
stopService(service);
}
};
private TimerTask ServiceIntervalTimerTask = new TimerTask() {
@Override
public void run() {
// remove old timer updates
mHandler.removeCallbacks(LocationUpdateTimerTask);
mHandler.removeCallbacks(SendDataStopLocationUpdatesTimerTask);
// Start TimerTasks delayed
mHandler.postDelayed(LocationUpdateTimerTask, 1000);
mHandler.postDelayed(SendDataStopLocationUpdatesTimerTask,
conf_LocationUpdatePeriodInSec * 1000);
}
};
@Override
public void onDestroy() {
super.onDestroy();
startDataCollectionServiceIntervallTimer.cancel();
startDataCollectionServiceIntervallTimer = null;
// Remove all kinds of updates
mHandler.removeCallbacks(LocationUpdateTimerTask);
mHandler.removeCallbacks(SendDataStopLocationUpdatesTimerTask);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startDataCollectionServiceIntervallTimer = new Timer(
"HUJIDataCollectionServiceStartTimer");
startDataCollectionServiceIntervallTimer.schedule(ServiceIntervalTimerTask,
1000L, conf_sampleTimeInMin * 60 * 1000L);
mHandler = new Handler();
return START_STICKY;
}
我從應用程序內調用服務。當然,當我關閉應用程序Alarmmanager和服務繼續工作。但在某個特定點上,它變得瘋狂! – Arnold
但爲什麼設置重複報警?如果你的服務繼續工作爲什麼重複報警?只需設置一個鬧鐘,看看這是否會改變任何... – Jovan