zl程序教程

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

当前栏目

【Android 进程保活】提升进程优先级 ( 使用前台 Service 提高应用进程优先级 | 启动相同 id 的第二个前台 Service 关闭通知 )

Android应用进程 使用 提升 启动 关闭 提高
2023-06-13 09:17:49 时间

文章目录

一、 前台 Service 通知问题


上一篇博客 【Android 进程保活】提升进程优先级 ( 使用前台 Service 提高应用进程优先级 | 效果展示 | 源码资源 ) 实现了一个前台 Service , 在通知栏 , 存在一个通知 ;

二、 设置 startForeground id 参数为 0


在开启 Service 时 , 调用的 startForeground(0, notification) 方法中 , 传入的第一个参数 id 如果设置为 0 , 此时就不会弹出通知栏 , 但是同样 , 进程会变成后台进程 ;

启动后没有通知 ,

按下 Home 键后查询 , 发现该应用就变成了普通后台应用 , 没有进程提权的效果 ;

三、 启动相同 id 的第二个前台 Service 关闭通知


不同版本的前台服务策略 :

  • API Level < 18 : 直接使用 startForeground(10, new Notification()) 代码启动即可 ;
            startForeground(10, new Notification());
  • API Level 18 ~ 25 : 直接使用 startForeground(10, new Notification()) 代码启动 , 但是必须启动两个前台服务进程 , 绑定相同的 id , 后一个服务开启后马上关闭 , 即可将通知栏移除 ;
            startForeground(10, new Notification());
            // API 18 ~ 25 以上的设备 , 启动相同 id 的前台服务 , 并关闭 , 可以关闭通知
            startService(new Intent(this, CancelNotificationService.class));
public class CancelNotificationService extends Service {
    public CancelNotificationService() {
    }

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

        startForeground(10, new Notification());
        stopSelf();
    }

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

}
  • API Level >= 26 : ① 无法关闭通知栏 ; ② 必须手动创建通知通道 , 以及完整参数的通知 ;
            // 创建通知通道
            NotificationChannel channel = new NotificationChannel("service",
                    "service", NotificationManager.IMPORTANCE_NONE);
            channel.setLightColor(Color.BLUE);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 正式创建
            service.createNotificationChannel(channel);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "service");
            Notification notification = builder.setOngoing(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setPriority(PRIORITY_MIN)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .build();

            // 开启前台进程 , API 26 以上无法关闭通知栏
            startForeground(10, notification);

1、 前台服务 1

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();


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            // startForeground();

            // 创建通知通道
            NotificationChannel channel = new NotificationChannel("service",
                    "service", NotificationManager.IMPORTANCE_NONE);
            channel.setLightColor(Color.BLUE);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 正式创建
            service.createNotificationChannel(channel);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "service");
            Notification notification = builder.setOngoing(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setPriority(PRIORITY_MIN)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .build();

            // 开启前台进程 , API 26 以上无法关闭通知栏
            startForeground(10, notification);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
            startForeground(10, new Notification());
            // API 18 ~ 25 以上的设备 , 启动相同 id 的前台服务 , 并关闭 , 可以关闭通知
            startService(new Intent(this, CancelNotificationService.class));

        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2){
            // 将该服务转为前台服务
            // 需要设置 ID 和 通知
            // 设置 ID 为 0 , 就不显示已通知了 , 但是 oom_adj 值会变成后台进程 11
            // 设置 ID 为 1 , 会在通知栏显示该前台服务
            // 8.0 以上该用法报错
            startForeground(10, new Notification());
        }
    }

    @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(10, notification);
    }

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

2、 关闭通知栏的服务

package kim.hsl.keep_progress_alive.foreground_service;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

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

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

        startForeground(10, new Notification());
        stopSelf();
    }

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

}

3、清单文件

<?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"/>

        <!-- 用于提权的前台进程, 关闭通知操作 -->
        <service
            android:name=".foreground_service.CancelNotificationService"
            android:enabled="true"
            android:exported="true"/>

    </application>

</manifest>

四、源码资源


源码资源 :