Android 7(API 25)及以前的版本
public void notify(View view) {
//点击通知时,所使用的Intent
Intent intent=new Intent(this,MainActivity.class);
PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);
//获取通知管理器对象
NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification=new Notification.Builder(this)
.setContentTitle("这是一条通知")
.setContentText("这是通知的正文")
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentIntent(pi)
.build();
//发送通知
manager.notify(1,notification);
}
Android 8+的版本
/**
*
* 创建两个频道
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
//当版本大于Oreo(Android 8.0)
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) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this, "chat")
.setContentTitle("收到一条聊天消息")
.setContentText("今天中午吃什么?")
.setWhen(System.currentTimeMillis())
.setSmallIcon(android.R.drawable.ic_input_add)
.setAutoCancel(true)
.build();
manager.notify(1, notification);
}
/**
*
* 这是一条普通级频道上的通知
*/
public void sendSubscribeMsg(View view) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this, "subscribe")
.setContentTitle("收到一条订阅消息")
.setContentText("地铁沿线30万商铺抢购中!")
.setWhen(System.currentTimeMillis())
.setSmallIcon(android.R.drawable.ic_input_add)
.setAutoCancel(true)
.build();
manager.notify(2, notification);
}