第一步申请权限:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
第二步:更改 myService
public class MyService extends Service {
private static final String TAG="MyService";
private static final String ID="channel_1";
private static final String NAME="前台服务";
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder {
public void startDownload(){
Log.d("MyService", "startDownload executed");
}
public int getProcess(){
Log.d("Myservice", "getProgredd executed");
return 0;
}
}
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("MyService", "onCreate executed");
if(Build.VERSION.SDK_INT>=26){
setForeground();
}else{
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d("MyService", "onDestroy executed");
super.onDestroy();
}
@TargetApi(26)
private void setForeground(){
NotificationManager manager=(NotificationManager)getSystemService (NOTIFICATION_SERVICE);
NotificationChannel channel=new NotificationChannel (ID,NAME,NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel (channel);
Notification notification=new Notification.Builder (this,ID)
.setContentTitle ("收到一条重要通知")
.setContentText ("这是重要通知")
.setSmallIcon (R.mipmap.ic_launcher)
.setLargeIcon (BitmapFactory.decodeResource (getResources (),R.mipmap.ic_launcher))
.build ();
startForeground (1,notification);
}
}
第三步,在启动服务时,加
if (Build.VERSION.SDK_INT >= 26) {
//android8.0以上通过startForegroundService启动service
startForegroundService(startIntent);
} else {
startService(startIntent);
}