我有用于在状态栏中显示通知的代码。我知道可以通过再次调用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;
}
答案 0 :(得分:1)
您必须使用AlarmManager并每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...
}
}
答案 1 :(得分:0)
使用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);