startForeground(1, new Notification());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("1", "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.setLightColor(Color.RED);
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mNotificationManager.createNotificationChannel(channel);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLockScreenReceiver);
unregisterReceiver(phoneReceiver);
stopForeground(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && mNotificationManager != null) {
mNotificationManager.cancelAll();
}
}
调用的时候
intent = new Intent(this, MusicService.class);
intent.setAction(MusicService.ACTION_Play);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
AndroidX 修改
Notification.Builder builder = new Notification.Builder(this.getApplicationContext());
// .setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
// .setSmallIcon(R.drawable.app) // 设置状态栏内的小图标
// .setContentTitle(getResources().getString(R.string.app_name))
// .setContentText("正在上传...") // 设置上下文内容
// .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
//---------------- 新增代码 --------------------------------------
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//修改安卓8.1以上系统报错
NotificationChannel notificationChannel = new NotificationChannel("1", "MusicService", NotificationManager.IMPORTANCE_MIN);
notificationChannel.enableLights(false);//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯
notificationChannel.setShowBadge(false);//是否显示角标
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
builder.setChannelId("1");
}
Notification notification = builder.build(); // 获取构建好的Notification
notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
startForeground(1, notification);