wjc
1 天以前 e7e48e1a65fdaa361e14e7e77e24043a63126bd6
app/src/main/java/com/hdl/photovoltaic/uni/MyForegroundService.java
@@ -1,18 +1,22 @@
package com.hdl.photovoltaic.uni;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.hdl.photovoltaic.R;
import java.util.List;
public class MyForegroundService extends Service {
@@ -29,21 +33,17 @@
        isRunning = true;
    }
//    @Override
//    public void onTaskRemoved(Intent rootIntent) {
//        super.onTaskRemoved(rootIntent);
//        isRunning = false;
    /// /        // 停止前台状态,移除通知
    /// /        stopForeground(true);  // true表示移除通知
    /// ///        // 停止服务
    /// ///        stopSelf();
//        // 1. 先移除前台状态(可选,但建议)
//        stopForeground(true);
//
//        // 2. 停止服务
//        stopSelf();
//    }
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        // 当应用从最近任务中移除时调用
        stopForeground(true);
        stopSelf();
        killAppProcess(this);
//        // 3. 结束进程
//        android.os.Process.killProcess(android.os.Process.myPid());
//        System.exit(0);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 创建通知
@@ -88,10 +88,41 @@
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
        // 清理资源
        stopForeground(true);
    }
    public static boolean isServiceRunning() {
        return isRunning;
    }
    /**
     * 关掉app所有进程
     *
     * @param context 上下文
     */
    private void killAppProcess(Context context) {
//        AppManagerUtils.getAppManager().finishAllActivity();
//        Log.d("===6666666","");
        try {
            android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> processInfos = manager.getRunningAppProcesses();
            // 先杀掉相关进程,最后再杀掉主进程
            for (android.app.ActivityManager.RunningAppProcessInfo runningAppProcessInfo : processInfos) {
                if ((runningAppProcessInfo.uid == android.os.Process.myUid()) && (runningAppProcessInfo.pid != android.os.Process.myPid())) {
                    try {
                        android.os.Process.killProcess(runningAppProcessInfo.pid);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            android.os.Process.killProcess(android.os.Process.myPid());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}