最近在着手研究android framework,在开发消息通知需求时遇到问题,无论是通过android模拟器或者是实体机器均无法推送通知,通知需求是通过主活动中的点击按钮触发消息通知,具体代码如下:
public void onClick(View v) {
switch (v.getId()) {
case R.id.send_notice:
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.
getActivity(this, 0, intent, 0);
NotificationManager manager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_png);
Log.d("MainActivity", String.valueOf((bitmap == null)));
Notification notification = new Notification.Builder(this, getString(R.string.app_name))
.setContentTitle("this is a content title")
.setContentText("this is a content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(bitmap)
.setContentIntent(pendingIntent)
.build();
Log.d("MainActivity", String.valueOf((manager == null)));
manager.notify(1, notification);
break;
default:
}
}
多方查阅资料,各种搜索仍未找出问题在那,logcat中出现提示日志:
D/skia: --- Failed to create image decoder with message 'unimplemented'
并不明白是什么问题,通过代码中添加两条日志,Log.d()判断manager和bitmap是否为null,首先得出的是bitmap确实是null,表明BitmapFactory.decodeResource图像解码存在问题,后查明是ic_launch这张系统图片存在同名xml文件,导致找不到图片进行解码,将图片重命名后再次运行,仍然不能推送消息。
意识到消息推送在android O以上系统中需要手动添加NotificationChannel实现:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(getString(R.string.app_name), getString(R.string.app_name), NotificationManager.IMPORTANCE_LOW);
mChannel.setDescription("notication channel");
mChannel.setShowBadge(false);
manager.createNotificationChannel(mChannel);
}
再次运行,已经可以完成消息的正常推送。记录之。