Android的初学者,现在已经在这个问题上苦苦挣扎了一段时间。有一个正在进行的通知,我想经常更新。可能每一秒。我知道这应该是可能的,因为我看过其他应用程序就像Toggle一样。但无论何时更新并且页面上还有其他通知,他们都会继续互相争斗。我已经研究过,但没有找到任何能够帮助我的东西。
我相信我一直遵循这些规则,希望避免这个问题:
private NotificationManager mNotificationManagerupdate;
private NotificationCompat.Builder mBuilderupdate;
/**
* Notification system that is used for this app. All we need to do is call this function
* when we need to trigger a notification.
*/
private void notification() {
times = System.currentTimeMillis();
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.iss_2011);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.setOngoing(true)
.setContentTitle("ISS Tracker")
.setContentText("ISS is about an hour away!")
.setSmallIcon(R.drawable.iss_2011)
.setLargeIcon(icon)
.setSound(soundUri)
.setWhen(times);
Intent resultIntent = new Intent(context, Locations.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(Locations.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1234, mBuilder.build());
mBuilderupdate = mBuilder;
mNotificationManagerupdate = mNotificationManager;
}
/**
* Continuously updates a notification that will display live results.
*
* @param time The difference between ISS' location to user's location
*/
private void updatemanager(final long time) {
timerupdate = new Timer();
timerupdate.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
notificationupdate(time);
}
}, 0, 1000);
}
/**
* Updates the manager and finishes off when time reaches zero.
*
* @param time The difference between ISS' location to user's location
*/
private void notificationupdate(long time) {
int finalseconds = (int) (time / 1000) - loop++;
if (finalseconds > 0) {
mBuilderupdate.setContentText("ISS is about " + finalseconds + " seconds away!");
} else if (finalseconds > -11) {
mBuilderupdate.setContentText("ISS is at your location! Ending in (" + (10 - Math.abs(finalseconds)) + ")");
} else {
timerupdate.cancel();
timerupdate.purge();
timerupdate = null;
loop = 0;
endnotification = true;
}
mBuilderupdate.setWhen(times);
Log.d(TAG, "When = " + times);
mNotificationManagerupdate.notify(1234, mBuilderupdate.build());
if (endnotification) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) context.getSystemService(ns);
nMgr.cancel(1234);
}
}