下面是点击通知就跳转activity,有显示横幅和普通通知两个。是根据APP是否在后台,如果在前台,就显示横幅通知。如果在后台,就显示普通通知。
因为横幅的API是Android 5.0才出现的。所以先判断版本。
isAppIsInBackground(context)是判断应用的前后台。
代码连接:https://www.jianshu.com/p/63cb7e03b5cc
/**
* 发送通知
*
* @param mActivity
* @param mBundle
*/
public void sendNotification(Class> mActivity, Bundle mBundle, String title, String content) {
Log.i("hpdgetui", android.os.Build.MANUFACTURER + " ");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
showCommonNotification(mActivity, mBundle, title, content);
} else {
//小米5的手机应用在前台会自动打开APP,后台会正常弹出横幅
if (android.os.Build.MANUFACTURER.equals("Xiaomi") || android.os.Build.MANUFACTURER.equals("HUAWEI") || android.os.Build.MANUFACTURER.equals("Meizu")) {
if (isAppIsInBackground(context)) {
showHangup(mActivity, mBundle, title, content);
} else {
showCommonNotification(mActivity, mBundle, title, content);
}
} else {
showHangup(mActivity, mBundle, title, content);
}
}
}
横幅通知
/**
* 显示横幅通知
*
* @param mActivity
* @param mBundle
* @param
*/
private void showHangup(Class> mActivity, Bundle mBundle, String title, String content) {
NotificationManager manger = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle(title);
builder.setContentText(Html.fromHtml(content));
builder.setDefaults(NotificationCompat.DEFAULT_ALL);
builder.setSmallIcon(R.mipmap.ielts_bro_app_icon);
Intent intent = new Intent(context, mActivity);
mBundle.putSerializable("class", mActivity);
intent.putExtras(mBundle);
intent.setFlags(
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
);
PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pIntent);
builder.setFullScreenIntent(pIntent, true);
builder.setAutoCancel(true);
Notification notification = builder.build();
manger.notify((int) System.currentTimeMillis(), notification);
}
普通通知
/**
* 显示普通通知
*
* @param mActivity
* @param mBundle
*/
private void showCommonNotification(Class> mActivity, Bundle mBundle, String title, String content) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ielts_bro_app_icon);
builder.setContentTitle(title);
builder.setContentText(Html.fromHtml(content));
builder.setAutoCancel(true).setDefaults(
NotificationCompat.DEFAULT_VIBRATE
| NotificationCompat.DEFAULT_SOUND
);
Intent intent = new Intent(context, mActivity);
intent.putExtras(mBundle);
intent.setFlags(
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
);
PendingIntent pendingIntent =
PendingIntent.getActivity(
context,
100,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(pendingIntent);
Notification n = builder.build();
NotificationManagerCompat managerCompat =
NotificationManagerCompat.from(context);
managerCompat.notify((int) System.currentTimeMillis(), n);
}