Android Notification在真机上失效

为了实现服务器信息发生变化时,App向用户发出通知这个功能,在网上学了下Notification类,但通知在模拟器上好好的,一到真机上测试,就怎么也不出来了。换了好多种不同的写法,都是失败,百度上也搜索不到相关的问题。上上下下搞了3,4个小时,最后还是自己捣鼓出来了,记录下。

关键问题出在消息渠道上,要为Builder设置消息渠道,上代码。

//创建消息渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "State";
            String channelName = "状态";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            createNotificationChannel(channelId, channelName, importance);
}

createNotificationChannel函数实现:

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

消息渠道已经创建好了,下面为Builder设置消息渠道

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this,"default");

/**
*  设置Builder
*/
mBuilder.setContentTitle("我是标题")
		.setChannelId("State")  //关键!一定要set,不然就失效
		.setContentText("我是内容")
		.setLargeIcon(BitmapFactory
		.decodeResource(getResources(), R.mipmap.ic_launcher))
		.setSmallIcon(R.mipmap.ic_launcher_round)
		.setWhen(System.currentTimeMillis())
		.setTicker("我是测试内容")
		.setDefaults(Notification.DEFAULT_SOUND);
notificationManager.notify(10, mBuilder.build());

你可能感兴趣的:(Java)