每半小时在android中更新一次通知
我有在状态栏中显示通知的代码。我知道更新可以通过再次调用每半小时在android中更新一次通知,android,Android,我有在状态栏中显示通知的代码。我知道更新可以通过再次调用setLatestEventInfo()完成,但我希望每半小时更新一次。 我如何记录时间? 有人知道这有什么作用吗? 我甚至想过使用计数器,它每半个小时递增一次,但再次检索时间是一个问题 String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns)
setLatestEventInfo()
完成,但我希望每半小时更新一次。我如何记录时间? 有人知道这有什么作用吗?
我甚至想过使用计数器,它每半个小时递增一次,但再次检索时间是一个问题
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.index1;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence notificationTitle = "My notification";
CharSequence notificationText = "Hello World!";
Intent notificationIntent = new Intent(this, NotificationAppActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, notificationTitle, notificationText, contentIntent);
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
}
您必须每30分钟使用并安排一次重复事件。然后,您需要处理此事件,并在广播接收器的onReceive()
中更新您的通知,但通常会向您的服务发送Intent
,以执行此任务
示例代码:
Intent intent = new Intent(this, MyAlarmBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
long recurring = (30 * 60000); // in milliseconds
am.setRepeating(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis(), recurring, sender);
您的MyAlarmBroadcastReceiver
是常规BroadcastReceiver
,代码位于onReceive()
。我更喜欢使用一个广播接收器,因此我还向意图中添加了一些附加数据,以便我的广播接收器知道它应该做什么,但如果您愿意,可以将其分离
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive( Context context, Intent intent ) {
// ... do what you need to do here...
}
}
使用alarmManager,如下面的示例所示:
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
您可以使用AlarmManager在30分钟后收到通知有没有更简单的方法?没有。AlarmManager非常简单。我可以在程序中使用AlarmManager?最好在函数中设置计数器,对吗?可以。但是它的用途很简单-你只需要告诉Alarm Manager-每30分钟给我一次
PendingEvent
。就这样。在通话中,除非应用程序被关闭或手机重新启动,否则您就完成了。是的,但AlarmManager n下有这么多功能,我不知道我们应该使用哪一个。