Android开发中,当应用程序在后台时,需要向用户发出一些信息提示用户,比如:未读的消息数,下载或更新完成后通知用户。 而我们开发者就是通过手机最上方的状态栏来传递通知信息,就用到了----Notification.
private void showNotification(String contentTitle, String displayDetail, AlarmInfo alarmInfo) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 在点击通知时发送的Intent
Intent hangIntent = new Intent(this, TabActivity.class);
hangIntent.putExtra("alarmInfo", JSONObject.toJSONString(alarmInfo));
PendingIntent hangPendingIntent = PendingIntent.getActivity(this, 1001, hangIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// 应用频道Id唯一值, 长度若太长可能会被截断,
String channelId = "channelId";
// 最长40个字符,太长会被截断
String channelName = "channelName";
// Android 8.0 以上需要添加通道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
manager.createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(this, channelId)
// 设置通知的标题(位于第一行)
.setContentTitle(contentTitle)
// 设置通知的文本(位于第二行)
.setContentText(displayDetail)
.setWhen(System.currentTimeMillis())
// 在点击通知时发送的Intent
.setContentIntent(hangPendingIntent)
// 通知布局中使用的小图标
.setSmallIcon(R.drawable.launcher)
// 设置显示在提示和通知中的大图标
// .setLargeIcon()
// 在通知栏点击我们定义的通知是否自动取消显示
.setAutoCancel(true)
// 推送包含震动、声音、亮屏等
.setDefaults(Notification.DEFAULT_ALL)
.build();
// NOTIFY_ID参数,尽量设置为全局唯一,不然在其他地方发起的通知将会覆盖这边通知栏
manager.notify(noticeId++, notification);
}
注意 有些做消息推送的功能,为了避免重复开启,若是前往的界面的启动模式为singleTask,则需要通过onNewIntent方法获取
// TabActivity.class中
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String alarmInfo = intent.getStringExtra("alarmInfo");
if (StrUtil.isNotEmpty(alarmInfo)) {
Intent intent1 = new Intent();
intent1.putExtra("alarmInfo", alarmInfo);
intent1.setClass(context, AlarmInfoActivity.class);
context.startActivity(intent1);
}
}
Q.E.D.