最近在着手研究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);
}
再次運行,已經可以完成消息的正常推送。記錄之。