1
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

####1.准备一个前台BackGroundService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package com.guoshikeji.xiaoxiangDriver.services;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

import com.guoshikeji.xiaoxiangDriver.MainActivity;
import com.guoshikeji.xiaoxiangDriver.R;

import static android.app.Notification.PRIORITY_MAX;
/**
* Created by tyl
* 2019/11/12/012
* Describe:
*/
public class BackGroundService extends Service {
Notification notification;
private Context mContext;
private static Thread uploadGpsThread;
private MediaPlayer bgmediaPlayer;
private boolean isrun = true;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mContext = this;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//1.通知栏占用,不清楚的看官网或者音乐类APP的效果
notification = new Notification.Builder(mContext)
.setSmallIcon(R.mipmap.icon_notifacation_log)
.setWhen(System.currentTimeMillis())
.setTicker(getResources().getString(R.string.app_name))
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText("正在后台运行")
.setOngoing(true)
.setPriority(PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.build();
/*使用startForeground,如果id为0,那么notification将不会显示*/
startForeground(2479, buildNotification());
//2.最关键的神来之笔,也是最投机的动作,没办法要骗过CPU
//这就是播放音乐类APP不被杀的做法,自己找个无声MP3放进来循环播放
if(bgmediaPlayer == null){
bgmediaPlayer = MediaPlayer.create(this,R.raw.slient);
bgmediaPlayer.setLooping(true);
bgmediaPlayer.start();
}
return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onDestroy() {
isrun = false;
stopForeground(true);
bgmediaPlayer.release();
stopSelf();
super.onDestroy();
}

private NotificationManager notificationManager;
private boolean isCreateChannel = false;
@SuppressLint("NewApi")
private Notification buildNotification() {
Notification.Builder builder = null;
Notification notification = null;

if (android.os.Build.VERSION.SDK_INT >= 26) {
if (null == notificationManager) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
String channelId = getPackageName();
if (!isCreateChannel) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"BackgroundLocation", NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.enableLights(false);//是否在桌面icon右上角展示小圆点
notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
notificationManager.createNotificationChannel(notificationChannel);
isCreateChannel = true;
}
builder = new Notification.Builder(getApplicationContext(), channelId);
} else {
builder = new Notification.Builder(getApplicationContext());
}
builder.setSmallIcon(R.mipmap.icon_notifacation_log)
.setColor(getResources().getColor(R.color.main_color))
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText("正在后台运行")
.setWhen(System.currentTimeMillis());
if (android.os.Build.VERSION.SDK_INT >= 16) {
notification = builder.build();
} else {
return builder.getNotification();
}
return notification;
}
}

###2. 在对应的activity里显示开启service

1
2
Intent forgroundService = new Intent(this,BackGroundService.class);
startService(forgroundService);

###3. 在AndroidManifest.xml文件里申明service

1
2
3
4
<service
android:name=".BackGroundService"
android:enabled="true"
android:exported="true" />