1,确保targetSdkVersion已经指定到了26或者更高
2,确保手机安卓8以上
完整代码
public class MyNotifications extends AppCompatActivity {
Context context;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
context = MyNotifications.this;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "chat";
String channelName = "聊天消息";
int importance = NotificationManager.IMPORTANCE_HIGH;
createNotificationChannel(channelId, channelName, importance);
channelId = "subscribe";
channelName = "订阅消息";
importance = NotificationManager.IMPORTANCE_DEFAULT;
createNotificationChannel(channelId, channelName, importance);
}
}
@TargetApi(Build.VERSION_CODES.O)
private void createNotificationChannel(String channelId, String channelName, int importance) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
public void sendChatMsg(View view) {
Intent intent = new Intent(MyNotifications.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MyNotifications.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this, "chat")
.setContentTitle("收到一条聊天消息")
.setContentText("今天中午吃什么?")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.img)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground))
.setAutoCancel(true)
.setContentIntent(pendingIntent)//点击跳转activity
.build();
manager.notify(1, notification);
}
public void sendSubscribeMsg(View view) {
RemoteViews customView = new RemoteViews(MyNotifications.this.getPackageName(),R.layout.music_layout);//自定义通知
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this, "subscribe")
.setContentTitle("收到一条订阅消息")
.setContentText("地铁沿线30万商铺抢购中!")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground))
.setAutoCancel(true)
.setCustomContentView(customView)//自定义
.build();
manager.notify(2, notification);
}
}
layout就两个按钮
转https://mp.weixin.qq.com/s/PG8XxHEHpijL4AMZ4AGP8g##