Android 创建悬停通知栏

Android 在API26之后NotificationCompat.Builder (Context context)被废弃,创建通知需要使用新的构造器NotificationCompat.Builder (Context context, String channelId)

so:

NotificationManager manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

String CHANNEL_ID = "com.example.test";//自定义的字符串
String CHANNEL_NAME = "TEST";
NotificationChannel notificationChannel = null;
NotificationCompat.Builder builder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.createNotificationChannel(notificationChannel);
}

Intent intent = new Intent(this, HomeActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder = new NotificationCompat.Builder(this, CHANNEL_ID).
        setContentTitle(getResources().getString(R.string.app_name)).
        setContentText(getResources().getString(R.string.notice_001)).
        setWhen(System.currentTimeMillis()).
        setSmallIcon(R.mipmap.app_icon).
        setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.app_icon)).
        setContentIntent(pendingIntent).setDefaults(NotificationCompat.FLAG_ONGOING_EVENT)
        .setPriority(Notification.PRIORITY_MAX);


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//SDK版本>=21才能设置悬挂式通知栏
    builder.setCategory(String.valueOf(Notification.FLAG_ONGOING_EVENT))
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setColor(getResources().getColor(R.color.white));
    Intent intent2 = new Intent();
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent2, 0);
    builder.setFullScreenIntent(pi, true);
}
Notification notification = builder.build();
manager.notify(1, notification);

你可能感兴趣的:(Android)