这是我如何在我的应用程序中使用 AlarmService 的演练。
设置一个 AlarmManager 在 x 分钟内触发。
响应警报,启动服务。
创建您的通知并让您的服务使用新的警报自行设置,以便在另外 x 分钟内再次触发。
该服务自行关闭。
1.
Intent alarmIntent = new Intent(this, MyAlarm.class);
long scTime = 60* 10000;// 10 minutes
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + scTime, pendingIntent);
2.
public class MyAlarm extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Alarm Recieved!", "YAAAY");
Intent i = new Intent(context, InviteService.class);
context.startService(i);
}
}
3.
public class InviteService extends IntentService
{
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public InviteService() {
super("InviteService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.logo;
CharSequence tickerText = "New Invite!";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_VIBRATE;
Context context = getApplicationContext();
CharSequence contentTitle = "Title";
CharSequence contentText = "Text";
Intent notificationIntent = new Intent(this, Destination.class);
Bundle partyBundle = new Bundle();
PendingIntent contentIntent = PendingIntent.getActivity(this, SOME_ID, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
int NOTIFICATION_ID = SOME_ID;
Log.d("NOTIFICATION_ID", "" + NOTIFICATION_ID);
mNotificationManager.notify(NOTIFICATION_ID, notification);
4.(同班)
Intent alarmIntent = new Intent(this, MyAlarm.class);
long scTime = 60*1000;//mins
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + scTime, pendingIntent);
stopService(intent);
}
}
希望这可以帮助!
编辑
为什么要使用服务?
在 BroadcastReceiver 中做太多处理是不明智的。虽然您可以在 BroadcastReciever 中进行一些处理,但在 Service 中执行此操作更安全,您可以在 StackOverflow 这个问题BroadcastReceiver vs Service中找到一些信息