我需要设置一次触发的重复闹钟,发起通知。
步骤:
我不确定警报系统是如何工作的。警报可能是沉默的,也许是振动。是否可以直接设置?
我是需要服务还是广播接收者才能完成这项工作?
基本上我只需要一些指针。我正确地考虑了这个吗?那里有一个教程(我还没找到任何东西)。提前谢谢。
答案 0 :(得分:10)
以下是我在应用中如何使用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中进行一些处理,但在服务中执行此操作更安全,您可以在此StackOverflow问题中找到一些信息BroadcastReceiver vs Service