Android通知版本判断,Android各版本使用通知的方法

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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值