Android NotificationChannel
在学习《Android 第一行代码》,第8章-多媒体—使用通知那块遇到了问题。
就是在Android o 以上的版本(api为26)在使用通知时,需要另外一个类–NotificationChannel。
在Android o之后app每发送一个通知都需要依附一个NotificationChannel,每个notification对象必须发送到指定的NotificationChannel,如果找不到channel,就会报错。
接下来看看如何使用。
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private NotificationManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendNotice = (Button)findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
@Override
@RequiresApi(api = Build.VERSION_CODES.O)
public void onClick(View view) {
switch (view.getId()){
case R.id.send_notice:
if(Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.O){
NotificationChannel notificationChannel = new NotificationChannel("channel","channelname",NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"channel").setContentTitle("This is content title")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
manager.notify(1, builder.build());
break;
default:
break;
}
}
}
NotificationChannel共三个参数,第一个参数是id,就是通知渠道的id,后面NotificationCompat.Builder使用哪个渠道就依靠此id来判断。第二个参数是通知渠道的名称。第三个参数是通知的重要程度。
通知渠道名称可以在应用的通知管理看到,如图: