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
package io.cordova.hellocordova;
 
import android.app.ActivityManager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.webkit.JavascriptInterface;
import android.widget.Toast;
 
import com.service.MyInteractionService;
import com.socket.MySocketClientThread;
 
import java.util.List;
 
import io.hybird.jsbridge.JsInterface;
 
/**
 * 监测Android app是否强制退出
 */
public class CheckExitService extends Service {
    private String packageName = "io.cordova.hellocordova";
 
 
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        MyInteractionService.isRunning = false;
 
        MyInteractionService service = MySocketClientThread.service;
        if(service != null){
            service.exitDeiviceConn();
        }
        //Toast.makeText(CheckExitService.this, "App要退出了", Toast.LENGTH_SHORT).show();
        super.onTaskRemoved(rootIntent);
    }
 
    //service异常停止的回调
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        ActivityManager activtyManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activtyManager.getRunningAppProcesses();
        for (int i = 0; i < runningAppProcesses.size(); i++) {
            if (packageName.equals(runningAppProcesses.get(i).processName)) {
                //Toast.makeText(this, "app还在运行中", Toast.LENGTH_LONG).show();
            }
        }
        return START_NOT_STICKY;
    }
 
    @Override
    public void onCreate() {
        super.onCreate();
        //Toast.makeText(CheckExitService.this, "App检测服务开启了", Toast.LENGTH_SHORT).show();
    }
 
}