zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

【Android 进程保活】提升进程优先级 ( 使用前台 Service 提高应用进程优先级 | 效果展示 | 源码资源 )

Android资源应用进程源码 提升 效果 提高
2023-09-27 14:29:03 时间





一、 使用前台 Service 提高应用进程优先级



上一篇博客 【Android 进程保活】提升进程优先级 ( 1 像素 Activity 提高进程优先级 | taskAffinity 亲和性说明 | 运行效果 | 源码资源 ) 使用了前台 Activity , 提升整个进程的优先级 ;

前台进程中除了前台显示的 Activity 之外 , 还有前台服务 , 即调用 startForeground 方法启动的服务 ;

按下 Home 键后 , 通过前台服务 , 让后台进程仍然是前台进程 ;



1、 前台 Service 代码


package kim.hsl.keep_progress_alive.foreground_service;

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.graphics.Color;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import kim.hsl.keep_progress_alive.R;

import static androidx.core.app.NotificationCompat.PRIORITY_MIN;

public class ForegroundService extends Service {
    public ForegroundService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // 将该服务转为前台服务
        // 需要设置 ID 和 通知
        // 设置 ID 为 0 , 就不显示已通知了 , 但是 oom_adj 值会变成后台进程 11
        // 设置 ID 为 1 , 会在通知栏显示该前台服务
        //startForeground(1, new Notification());

        startForeground();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    /**
     * 启动前台服务
     */
    private void startForeground() {
        String channelId = null;
        // 8.0 以上需要特殊处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channelId = createNotificationChannel("kim.hsl", "ForegroundService");
        } else {
            channelId = "";
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
        Notification notification = builder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(PRIORITY_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(1, notification);
    }

    /**
     * 创建通知通道
     * @param channelId
     * @param channelName
     * @return
     */
    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(String channelId, String channelName){
        NotificationChannel chan = new NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        service.createNotificationChannel(chan);
        return channelId;
    }
}


2、 前台 Service 代码


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kim.hsl.keep_progress_alive">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Keep_Progress_Alive">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!--
            设置最近任务列表中不显示该 Activity 组件 ( 不要被用户察觉 )
            android:excludeFromRecents="true"

            设置 Activity 亲和性
            让该界面在一个独立的任务栈中 , 不要与本应用的其它任务栈放在一起
            避免解除锁屏后 , 关闭 1 像素界面 , 将整个任务栈都唤醒
            android:taskAffinity="kim.hsl.keep_progress_alive.alive"
        -->
        <activity
            android:name=".one_pixel_activity.OnePixelActivity"
            android:excludeFromRecents="true"
            android:taskAffinity="kim.hsl.keep_progress_alive.onepixel"
            android:theme="@style/OnePixelActivityTheme" />

        <!-- 用于提权的前台进程 -->
        <service
            android:name=".foreground_service.ForegroundService"
            android:enabled="true"
            android:exported="true"/>

    </application>

</manifest>


3、 启动服务


=package kim.hsl.keep_progress_alive;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;

import kim.hsl.keep_progress_alive.foreground_service.ForegroundService;
import kim.hsl.keep_progress_alive.one_pixel_activity.KeepProgressAliveManager;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 1 像素 Activity 提升应用权限
        // 注册广播接收者 , 1 像素 Activity 启动的 广播接收者
        //KeepProgressAliveManager.getmInstance().registerReceiver(this);

        // 通过前台 Service 提升应用权限
        // 启动普通 Service , 但是在该 Service 的 onCreate 方法中执行了 startForeground
        // 变成了前台 Service 服务
        startService(new Intent(this, ForegroundService.class));

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 取消注册广播接收者, 也可以不取消注册
        //KeepProgressAliveManager.getmInstance().registerReceiver(this);
    }
}




二、效果展示



启动应用 ,

在这里插入图片描述

查看 Logcat 中的 PID 为 30014 30014 30014 ,

在这里插入图片描述
查询进程 oom_adj 值 , 0 0 0 , 前台进程 ;

在这里插入图片描述

C:\Users\octop>adb shell
walleye:/ $ su
walleye:/ # cat /proc/30014/oom_adj
0
walleye:/ #

点击 Home 键 ,

在这里插入图片描述

查询 oom_adj 值 , 4 4 4 , 在 【Android 进程保活】oom_adj 值 ( oom_adj 值对应的进程优先级 | oom_adj 值动态改变 | 进程保活优化方向 ) 可以看到该进程是后台重量级进程 , 比后台进程 9 9 9 ~ 15 15 15 优先级高 ;

在这里插入图片描述

C:\Users\octop>adb shell
walleye:/ $ su
walleye:/ # cat /proc/30014/oom_adj
0
walleye:/ # cat /proc/30014/oom_adj
4
walleye:/ #




三、源码资源



源码资源 :