How to stop an alarm service when the app stops?
I have an App wi开发者_如何学编程th a workflow that calls many activities, some of them it finishes and others leaves them active as the user progresses through it. BUT I cannot switch off my alarm service which continues even when the home button is actuated and the app killed.
Oh sure - the force close in settings will stop the alarm service very well (its the only way to kill it). I cannot stop alarm from my app program since nothing tells me when the app has been closed.
None of the life cycle methods onDestroy() or on Stop() work because the home button can be actuated during any of 15 activities and onDestroy() is not called for a long time after on any activity.
BUT I cannot switch off my alarm service which continues even when the home button is actuated and the app killed.
Then do not register the alarm. AlarmManager
is designed to execute your code periodically when your code is not already running. For something that is purely within an activity, use postDelayed()
.
When you press the home button, your app isn't--and isn't supposed to--shut down. It is "frozen" by a call to onSaveInstanceState(Bundle)
. If you click on your app icon, it will be restarted and resumed just as if there had been a giant pause in the system clock (or, if it was killed off by the system, re-created from the bundle you set in onSaveInstanceState
). Typically you would turn suspend or cancel time-related activity in onPause
, because, in a sense, time stops for your app at that point.
What are you using alarms for that they need to be stopped when the app exits? The whole point of them, I thought, was to invoke something in your app up at a particular time even if it wasn't running.
Just do like this....
AlarmManager alarm;
PendingIntent pintent;
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(this, TestService.class);
pintent = PendingIntent.getService(this, 0, intent, 0);
alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int i;
i=30;
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), i* 1000, pintent);
System.out.println("service going to start-----------");
startService(new Intent(getBaseContext(), TestService.class)); // Here start your service
If you want to stop your service means you should stop your alarm service once. In onBackPressed() method's ok button would be finish your activity. Within that button you should add the following code.
alarm.cancel(pintent);
This will stop your service add alarm when you exit from your application. All the best.
精彩评论