我以前从未使用过服务。所以,在互联网上关注了几个恶魔之后,我的实现是这样的:
在我的 MainActivity 的 onResume() 中,我以这种方式启动服务:
protected void onResume() {
super.onResume();
startService(new Intent(MainActivity.this, NotificationsService.class));
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, NotificationsService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
am.cancel(pi);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60000, 60000, pi);
}
我的 NotificationsService 类是:
public class NotificationsService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleIntent(intent);
return START_NOT_STICKY;
}
private NotificationManager nm;
private WakeLock mWakeLock;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
mWakeLock.release();
}
private void showNotification() {
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,
"Notification Ticker", System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL;
Date date = new Date(System.currentTimeMillis());
Intent i = new Intent(this, NotificationsActivity.class);
i.putExtra("notification",
"This is the Notification " + date);
i.putExtra("notifiedby", "xyz");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this, "xyz",
"This is the Notification", contentIntent);
nm.notify(R.string.service_started, notification);
}
private class PollTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
showNotification();
return null;
}
@Override
protected void onPostExecute(Void result) {
stopSelf();
}
}
private void handleIntent(Intent intent) {
// obtain the wake lock
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"NotificationsService");
mWakeLock.acquire();
// check the global background data setting
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
if (!cm.getBackgroundDataSetting()) {
stopSelf();
return;
}
new PollTask().execute();
}
}
在 NotificationsActivity 中,我得到了 Extras 并显示了。这些 Extras 有一个时间戳,我每分钟(60000 毫秒)调用一次 showNotifications() 方法。
问题:
- 我从 Service Extras 获得的 NotificationsActivity 中显示的时间戳是第一个通知的时间戳
例如,如果第一次通知的时间是上午 10:10:10,那么活动中的时间总是上午 10:10:10。但是在“通知”面板中,它会为每分钟创建的每个通知显示更新的通知,例如上午 10:15:10。
- 如果我每分钟设置一次通知,我希望通知是分开的。相反,它只是替换了以前的通知。或者最好是来自 myApp 的 10 个通知。
如何获得这些?
主要是我想知道为什么时间戳没有更新?