如何解決android 通知欄不顯示的問題


android 8.0 以后的版本,在創建通知欄的時候,加了一個channelId的東西。要想在上述版本中顯示通知,總共分兩步

1.創建Channel

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  String channelId = "whatever"; //根據業務執行
  String channelName = "whatever conent"; //這個是channelid 的解釋,在安裝的時候會展示給用戶看
  int importance = NotificationManager.IMPORTANCE_HIGH;
  createNotificationChannel(channelId, channelName, importance);

}

 

2.引用

Notification notification = new Notification.Builder(this,"whatever") //引用加上channelid
  .setSmallIcon(R.drawable.donkey)
  .setWhen(System.currentTimeMillis())
  .setContentTitle("隨便")
  .setContentText("隨隨便便寫")
  .setContentIntent(pendingIntent)
  .build();

 

為了兼容android所有版本,最好在代碼里做一下適配

 

 

manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Intent intent = new Intent(this, AudioPlayerActivity.class);
intent.putExtra("Notifiction",true);


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  String channelId = "whatever"; //根據業務執行
  String channelName = "whatever conent"; //這個是channelid 的解釋,在安裝的時候會展示給用戶看
  int importance = NotificationManager.IMPORTANCE_HIGH;
  createNotificationChannel(channelId, channelName, importance);

}

PendingIntent pendingIntent = PendingIntent.getActivity(this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = null;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){

  notification = new Notification.Builder(this,"whatever") //引用加上channelid
    .setSmallIcon(R.drawable.donkey)
    .setWhen(System.currentTimeMillis())
    .setContentTitle("隨便")
    .setContentText("隨隨便便寫")
    .setContentIntent(pendingIntent)
    .build();
}else{
  notification = new Notification.Builder(this)
    .setSmallIcon(R.drawable.donkey)
    .setWhen(System.currentTimeMillis())
    .setContentTitle("隨便")
    .setContentText("隨隨便便寫")
    .setContentIntent(pendingIntent)
    .build();
}

manager.notify(1,notification);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM