a
554325746@qq.com
2019-12-25 603cb36a5123e46656b06a5deb8d7ac7ff81307f
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package com.basic.security.service;
 
import android.app.ActivityManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.text.TextUtils;
 
import com.basic.security.activity.MainActivity;
import com.basic.security.base.BaseApplication;
import com.basic.security.utils.Constants;
 
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";
    long lastOnReceive = 0;
    BroadcastReceiver keepLifeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            lastOnReceive = System.currentTimeMillis();
//            System1.out.println("KeepLifeService.onReceive");
        }
    };
    private String mPackName;
    private ActivityManager mActivityManager;
    private boolean running = false;
 
    /**
     * 获取当前进程名称
     *
     * @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;
    }
 
    @Override
    public void onCreate() {
        running = true;
        super.onCreate();
        IntentFilter intentFilter = new IntentFilter("keepLife");
        registerReceiver(keepLifeReceiver, intentFilter);
        mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String process = getProcessName();
        mPackName = getPackageName();
        BaseApplication.getApplication().executorService.execute(() -> {
            while (running) {
                try {
//                        System1.out.println("KeepLifeService.run " + Thread.currentThread().getId());
                    SystemClock.sleep(2 * 1000);
                    if (Constants.autoRestart) {
                        boolean isRun = isRunningProcess(mActivityManager, mPackName);
                        if (lastOnReceive != 0 && System.currentTimeMillis() - lastOnReceive > 10 * 1000) {
                            isRun = false;
                        }
//                            Log.i(TAG, String.format("onCreate: %s %s pid=%d uid=%d isRun=%s", mPackName, process, Process.myPid(), Process.myUid(), isRun));
                        if (!isRun) {
                            Intent intent = getPackageManager().getLaunchIntentForPackage(mPackName);
                            if (intent != null) {
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
 
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            BaseApplication.getApplication().executorService.execute(() -> {
                while (running) {
//                    System1.out.println("服务正在运行..." + Thread.currentThread().getId());
                    try {
                        Thread.sleep(2 * 1000);
                        if (Constants.autoRestart) {
                            boolean isRun = isRunningProcess(mActivityManager, mPackName);
//                            Log.i(TAG, String.format("onCreate: %s %s pid=%d uid=%d isRun=%s", mPackName, process, Process.myPid(), Process.myUid(), isRun));
                            if (lastOnReceive != 0 && System.currentTimeMillis() - lastOnReceive > 10 * 1000) {
                                isRun = false;
                            }
                            if (!isRun) {
                                Intent intent1 = getPackageManager().getLaunchIntentForPackage(mPackName);
                                if (intent1 != null) {
                                    intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(intent1);
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            Notification.Builder builder = new Notification.Builder(this.getApplicationContext());
            Intent nfIntent = new Intent(this, MainActivity.class);
            builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0))
                    //设置通知栏大图标
                    .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), com.basic.security.utils.RUtils.R_drawable_back))
                    //设置服务标题
                    .setContentTitle("服务")
                    //设置状态栏小图标
                    .setSmallIcon(com.basic.security.utils.RUtils.R_drawable_back)
                    //设置服务内容
                    .setContentText("服务")
                    //设置通知时间
                    .setWhen(System.currentTimeMillis());
            Notification notification = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                notification = builder.build();
            }
            //设置通知的声音
            notification.defaults = Notification.DEFAULT_SOUND;
            startForeground(110, notification);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(keepLifeReceiver);
        running = false;
        stopForeground(true);
//        System1.out.println("KeepLifeService.onDestroy");
    }
}