private void showInspectorRecordNotification() {
RemoteViews customView = new RemoteViews(context.getPackageName(), R.layout.view_custom);
customView.setTextViewText(R.id.tvName_inspectPlan, planInfo.convertlineId2lineName(context, MyApplication.getInstance().getAppData().getUserId()));
customView.setTextViewText(R.id.tvTime_inspectPlan, planInfo.getPlanYm());
customView.setTextViewText(R.id.tvPlanSate_inspectPlan, planInfo.convertstateId2stateText(context));
NotificationCompat.Builder mBuilder = new Builder(context);
mBuilder.setContent(customView)
.setContentIntent(getDefalutIntent(PendingIntent.FLAG_UPDATE_CURRENT))
.setWhen(System.currentTimeMillis())
.setTicker("")
.setPriority(Notification.PRIORITY_DEFAULT)
.setOngoing(false)
.setSmallIcon(R.mipmap.icon);
Notification notify = mBuilder.build();
notify.contentView = customView;
notify.flags |= Notification.FLAG_AUTO_CANCEL; // 点击通知后通知栏消失
// 通知id需要唯一,要不然会覆盖前一条通知
int notifyId = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notifyId, notify);
}
@Override
public void onReceive(Context context, Intent intent) {
if (null == mNotificationManager) {
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
this.context = context;
Bundle bundle = intent.getExtras();
Util.soutLong(TAG, "onReceive - " + intent.getAction());
if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {//注册
Util.soutLong(TAG, "JPush用户注册成功");
} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
Util.soutLong(TAG, "接受到推送下来的自定义消息");
// 在这里显示自定义通知
} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
Util.soutLong(TAG, "接受到推送下来的通知");
// 这里会显示极光推送默认的通知,自定义能力有限
}
}
效果是可以实现,不过当发送的通知大于一条的时候,第二条通知会把第一条通知覆盖。即只会显示一条通知,查了一些资料后终于找到原因:
int notifyId = (int) System.currentTimeMillis(); 发送通知的 notifyId 需要唯一通知才不会被覆盖,否则系统认为是在更新通知
补充:前面的方法解决了推送只显示一条的问题,在推送多条通知的时候假如数据类型相同的又会出现一个问题:前面的通知内容会被后面推送的通知内容所覆盖:最终发现问题出在 PendingIntent.getActivity(参数1, 参数2, 参数3, 参数4);方法。 该方法有四个参数,问题主要出在第二个参数,API文档里虽然说是未被使用的参数(给出的例子也直接写0的),实际上是通过该参数来区别不同的Intent的,如果通知的第二个参数每次都相同,就会覆盖掉之前的Intent了。所以总是获取到最后一个Intent。
getDefalutIntent代码如下:
/**
* 构造一个打开通知的Intent
*
* @param flags
* @return
*/
private PendingIntent getDefalutIntent(int flags) {
Intent transferIntent = new Intent(context, LoadDataEmptyActivity.class);
transferIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
transferIntent.putExtra(PushReceiverConstant.KEY_FORM_TYPE, pushType);
// 第二个参数不能写死,可以写一个随机数或者是时间毫秒数 保证唯一
PendingIntent pendingIntent = PendingIntent.getActivity(context, (int)(Math.random() * 100), transferIntent, flags);
return pendingIntent;
}