Android8.0之后Service 启动前台服务并弹出通知
程序员文章站
2024-02-29 19:10:58
...
Service使用示例:Android使用Service播放音乐
注:8.0以上播放网络音乐用 https
Android8.0之后Service的启动方式有变:Android 8.0启动后台服务
具体写法入下:
1、首先修改启动方式
if (Build.VERSION.SDK_INT >= 26) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
2、其次在service里调用context.startForeground(SERVICE_ID, builder.getNotification());
我是在service的onCreate中调用的,示例:
/**
* Oreo不用Priority了,用importance
* IMPORTANCE_NONE 关闭通知
* IMPORTANCE_MIN 开启通知,不会弹出,但没有提示音,状态栏中无显示
* IMPORTANCE_LOW 开启通知,不会弹出,不发出提示音,状态栏中显示
* IMPORTANCE_DEFAULT 开启通知,不会弹出,发出提示音,状态栏中显示
* IMPORTANCE_HIGH 开启通知,会弹出,发出提示音,状态栏中显示
*/
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder ;
String CHANNEL_ID = "my_channel_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ //Android 8.0适配
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);//如果这里用IMPORTANCE_NOENE就需要在系统的设置里面开启渠道, //通知才能正常弹出
manager.createNotificationChannel(channel);
builder = new NotificationCompat.Builder(this,String.valueOf(CHANNEL_ID));
}else{
builder = new NotificationCompat.Builder(this);
}
builder.setContentTitle("this is content title") //指定通知栏的标题内容
.setContentText("this is content text") //通知的正文内容
.setWhen(System.currentTimeMillis()) //通知创建的时间
.setSmallIcon(R.drawable.ic_launcher_background) //通知显示的小图标,只能用alpha图层的图片进行设置
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_background));
Notification notification = builder.build() ;
startForeground(1, notification);
上一篇: MySQL优化之如何了解SQL的执行频率