场景
Android系统8.0及以上,开启Service必须使用startForegroundService(Intent intent)方法,对应的Service则必须设置startForeground(int id, Notification notification),因而我们必须创建一个通知,这样在服务运行当中,会一直显示一条“xx正在运行”类似的通知。
目标
消除“xx正在运行”的通知内容
解决方案
大体思路是:一个最后保留的MyService,一个辅助消除通知的MyService1, 利用 MyService去绑定MyService1,startForeground变为前台服务,注意一定要使用一样的Notification ID,然后MyService1取消前台效果stopForeground从而删除通知。
- AndroidManifest 添加权限
<!--service前台服务-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
- 业务服务
package com.example.demo;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.RequiresApi;
/**
* @author: ding xujun
* @created on: 2020/12/10 23:01
* @project: demo
*/
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public class Myservice extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onCreate() {
super.onCreate();
Log.d("Myservice=======", "onCreate");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground