我以前從未使用過服務。因此,互聯網上的以下幾個惡魔後我的實現是這樣的:Android:使用服務的通知
在我的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()方法。
問題:
- 我在NotificationsActivity,這是我從服務額外獲得顯示時間戳是第一通知
EG的時間戳,如果是10:上午10點10分,第一次通知在活動中始終是10:10:10。但是在通知面板中,它顯示的是每分鐘創建的每個通知都會更新的一個,比如10:15:10 A.M。
- 如果我每分鐘都設置通知,我希望通知是分開的。相反,它只是取代以前的通知。或者最好是像myApp的10個通知。
如何獲取這些?
主要我想知道爲什麼時間戳沒有得到更新?
您可以在發佈並添加此類信息後編輯您的問題。 – HaskellElephant