.新建个 KeepLifeService
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;
public class KeepLifeService extends Service {
private static final String TAG="KeepLifeService";
private String mPackName;
private ActivityManager mActivityManager;
@Override
public void onCreate() {
super.onCreate();
mActivityManager =(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
String process=getProcessName();
mPackName =getPackageName();
boolean isRun=isRunningProcess(mActivityManager,mPackName);
if(!isRun){
Intent intent = getPackageManager().getLaunchIntentForPackage(mPackName);
if(intent!=null){
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 获取当前进程名称
*
* @return
*/
public static String getProcessName() {
try {
File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
return processName;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 进程是否存活
* @return
*/
public static boolean isRunningProcess(ActivityManager manager,String processName) {
if(manager==null)
return false;
List<ActivityManager.RunningAppProcessInfo> runnings = manager.getRunningAppProcesses();
if (runnings != null) {
for (ActivityManager.RunningAppProcessInfo info : runnings) {
if(TextUtils.equals(info.processName,processName)){
return true;
}
}
}
return false;
}
}
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
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
在 MainActivity 里调用
startService(new Intent(this,KeepLifeService.class));
1
最后在 AndroidManifest.xml
<service android:name=".KeepLifeService" android:process=":keepLife" />
1