2017-06-08 11 views
30

とNotificationCompat私は新しいchannelIdを取るコンストラクタが、どのようcompatの通知を取ると、createNotificationChannel以来NotificationChannelでそれを使用する方法を参照していますAndroidのOさんNotification Channelsは、API 26

でNotificationCompatを使用する方法についての情報を参照してくださいいけません:NotificationChannelオブジェクト

答えて

63

NotificationChannel APIのみの場合> = 26

public void initChannels(Context context) { 
    if (Build.VERSION.SDK_INT < 26) { 
     return; 
    } 
    NotificationManager notificationManager = 
      (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
    NotificationChannel channel = new NotificationChannel("default", 
                  "Channel name", 
                  NotificationManager.IMPORTANCE_DEFAULT); 
    channel.setDescription("Channel description"); 
    notificationManager.createNotificationChannel(channel); 
} 

を作成してから、ちょうど使用して取り10

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "default"); 
通知は、API 26(チャンネルあり)と下位(なし)の両方で動作しています。

+0

チャンネルにサウンド/ライト/バイブレーションを設定する必要がありますか、それとも互換ビルダーでそれを行うのですか? – tyczj

+1

サウンド/ライト/バイブレーションを設定する必要はありません。たとえば、カスタムサウンド/ライト/バイブレーションや通知カスタム振動などのチャンネルがある場合はどうなるでしょうか。 API 26では、そのチャンネルがちょうど無視されているため、 – stankocken

+0

@ user5195185 android support compat 26.0.2(build.gradleの 'com.android.support:support-compat:26.0.2''をコンパイルしてください)を使ってみてください –

5

宣言通知マネージャ:

final NotificationManager mNotific=    
    (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 

    CharSequence name="Ragav"; 
    String desc="this is notific"; 
    int imp=NotificationManager.IMPORTANCE_HIGH; 
    final String ChannelID="my_channel_01"; 

通知チャンネル

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
    { 
     NotificationChannel mChannel = new NotificationChannel(ChannelID, name, 
    imp); 
      mChannel.setDescription(desc); 
      mChannel.setLightColor(Color.CYAN); 
      mChannel.canShowBadge(); 
      mChannel.setShowBadge(true); 
      mNotific.createNotificationChannel(mChannel); 
     } 

    final int ncode=101; 

    String Body="This is testing notific"; 

ユーザーに通知NotificationManager

 Notification n= new Notification.Builder(this,ChannelID) 
       .setContentTitle(getPackageName()) 
       .setContentText(Body) 
       .setBadgeIconType(R.mipmap.ic_launcher) 
       .setNumber(5) 
       .setSmallIcon(R.mipmap.ic_launcher_round) 
       .setAutoCancel(true) 
       .build(); 

通知ビルダー:

  mNotific.notify(ncode, n); 
関連する問題