1. 程式人生 > >android O 實現通知併兼容低版本

android O 實現通知併兼容低版本

在主活動中實現按鈕彈出通知

在的onCreate中首先繫結按鈕

Button sendNotice =  (Button)findViewById(R.id.button_send_notice);
sendNotice.setOnClickListener(this);

的onClick

@Override
public void onClick(View view) {
    //判斷sdk 當app版本為O或者以上時建立通知渠道
    if(Build.VERSION.SDK_INT >= 26)
        createChannel();
    switch (view.getId()){
        case R.id.button_send_notice:
            Intent intent = new Intent(this, NotificationActivity.class);
            PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
            Notification notification = new NotificationCompat.Builder(this, "channel_01")
                    .setContentTitle("This is content title")
                    .setContentText("Tis is content")
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                    .setContentIntent(pi)
                    .build();
            NotificationManager  manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            manager.notify(1, notification);
            break;
        default:
            break;
    }
}

建立通知渠道的函式封裝

@RequiresApi(api=26)
public void createChannel(){

    NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    //通知渠道組的id
    String group = "group_id";
    // 使用者可見的通知渠道組名稱.
    CharSequence group_name = getString(R.string.group_name);
    //建立通知渠道組
    manager.createNotificationChannelGroup(new NotificationChannelGroup(group, group_name));

    /**
     * 建立通知渠道1
     */

    //渠道id
    String id = "channel_01";
    //使用者可以看到的通知渠道的名字
    CharSequence name = getString(R.string.channel_name);
    //使用者可以看到的通知渠道的描述
    String description = getString(R.string.channel_description);
    int importance = NotificationManager.IMPORTANCE_HIGH;
    NotificationChannel channel = new NotificationChannel(id, name, importance);
    //配置通知渠道的屬性
    channel.setDescription(description);
    //設定通知出現時的閃燈(如果android裝置支援的話)
    channel.enableLights(true);
    channel.setLightColor(Color.GREEN);
    //設定通知出現時的震動(如果androd裝置支援的話)
    channel.enableVibration(true);
    channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});
    //繫結通知渠道組
    channel.setGroup(group);
    //在notificationmanager中建立該通知渠道
    manager.createNotificationChannel(channel);
}