package com.basic.security.service;
|
|
import android.app.ActivityManager;
|
import android.app.Notification;
|
import android.app.NotificationChannel;
|
import android.app.NotificationManager;
|
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.graphics.Color;
|
import android.os.Build;
|
import android.os.IBinder;
|
import android.os.SystemClock;
|
import android.support.annotation.Nullable;
|
import android.support.v4.app.NotificationCompat;
|
import android.text.TextUtils;
|
|
import com.basic.security.R;
|
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();
|
// System.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 {
|
// System.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) {
|
BaseApplication.getApplication().executorService.execute(() -> {
|
while (running) {
|
// System.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();
|
}
|
}
|
});
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
|
startMyOwnForeground();
|
else {
|
// startForeground(1, new Notification());
|
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(), R.drawable.back))
|
//设置服务标题
|
.setContentTitle("服务")
|
//设置状态栏小图标
|
.setSmallIcon(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);
|
}
|
|
return super.onStartCommand(intent, flags, startId);
|
}
|
private void startMyOwnForeground(){
|
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
|
String channelName = "My Background Service";
|
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
|
chan.setLightColor(Color.BLUE);
|
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
|
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
|
assert manager != null;
|
manager.createNotificationChannel(chan);
|
|
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
|
Notification notification = notificationBuilder.setOngoing(true)
|
.setSmallIcon(R.drawable.back)
|
.setContentTitle("App is running in background")
|
.setPriority(NotificationManager.IMPORTANCE_MIN)
|
.setCategory(Notification.CATEGORY_SERVICE)
|
.build();
|
startForeground(2, notification);
|
}
|
|
@Override
|
public void onDestroy() {
|
super.onDestroy();
|
unregisterReceiver(keepLifeReceiver);
|
running = false;
|
stopForeground(true);
|
// System.out.println("KeepLifeService.onDestroy");
|
}
|
}
|