我创建了自己的消息队列系统。不使用单个id,但能够实现我想要的
如果同时发出多个通知请求,则只会显示 1 条消息。每条消息都会轮流出现。没有消息丢失。
this.blockingQueue.offer(message);
这是完整的消息队列系统。
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
executor.submit(new NotificationTask());
}
private class NotificationTask implements Runnable {
@Override
public void run() {
while (!executor.isShutdown()) {
try {
String message = blockingQueue.take();
notification(message);
// Allow 5 seconds for every message.
Thread.sleep(Constants.NOTIFICATION_MESSAGE_LIFE_TIME);
} catch (InterruptedException ex) {
Log.e(TAG, "", ex);
// Error occurs. Stop immediately.
break;
}
}
}
}
@Override
public void onDestroy() {
// Will be triggered during back button pressed.
super.onDestroy();
executor.shutdownNow();
try {
executor.awaitTermination(100, TimeUnit.DAYS);
} catch (InterruptedException ex) {
Log.e(TAG, "", ex);
}
}
private void notification(String message) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this.getActivity())
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(this.getString(R.string.app_name))
.setTicker(message)
.setContentText(message)
.setAutoCancel(true)
.setOnlyAlertOnce(true);
// Do we need to have sound effect?
final NotificationManager mNotificationManager =
(NotificationManager) this.getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
final int id = atomicInteger.getAndIncrement();
mNotificationManager.notify(id, mBuilder.build());
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new NotificationManagerCancelRunnable(mNotificationManager, id), Constants.NOTIFICATION_MESSAGE_LIFE_TIME);
}
// Use static class, to avoid memory leakage.
private static class NotificationManagerCancelRunnable implements Runnable {
private final NotificationManager notificationManager;
private final int id;
public NotificationManagerCancelRunnable(NotificationManager notificationManager, int id) {
this.notificationManager = notificationManager;
this.id = id;
}
@Override
public void run() {
notificationManager.cancel(id);
}
}
// For notification usage. 128 is just a magic number.
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(128);
private final AtomicInteger atomicInteger = new AtomicInteger(0);