AlarmService_Servicepublic class AlarmService_Service extends android.app.Service implements RunnableThis is an example of implementing an application service that will run in
response to an alarm, allowing us to move long duration work out of an
intent receiver. |
Fields Summary |
---|
private final android.os.IBinder | mBinder | private android.app.NotificationManager | mNM |
Methods Summary |
---|
public android.os.IBinder | getBinder()
return mBinder;
| protected void | onCreate()
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// This is who should be launched if the user selects our persistent
// notification.
Intent intent = new Intent(this, AlarmService.class);
// We are going to display a notification for the entire time that we
// are running.
mNM.notifyWithText(R.string.alarm_service_started,
getText(R.string.alarm_service_started),
NotificationManager.LENGTH_SHORT,
new Notification(
R.drawable.stat_sample,
getText(R.string.alarm_service_label),
intent,
null,
null));
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block.
Thread thr = new Thread(null, this, "AlarmService_Service");
thr.start();
| protected void | onDestroy()
// Cancel the persistent notification.
mNM.cancel(R.string.alarm_service_started);
// Tell the user we stopped.
mNM.notifyWithText(R.string.alarm_service_finished,
getText(R.string.alarm_service_finished),
NotificationManager.LENGTH_SHORT,
null);
| public void | run()
// Normally we would do some work here... for our sample, we will
// just sleep for 30 seconds.
long endTime = System.currentTimeMillis() + 15*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (mBinder) {
try {
mBinder.wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
// Done with our work... stop the service!
this.stopSelf();
|
|