Android前台服务保活App(伪)
填写昵称已被占用
编辑于 2021年06月21日 21:49
收录于文集
共1篇

先说一下为什么是伪保活,现在的手机系统都是各家厂商深度定制的系统,理论上只要用户不手动把软件关闭,你的app是可以一直运行的。(有一种情况除外,官方解释:运行内存严重不足时,系统会干掉后台程序。但是前台服务一般不会干掉,可以把重要逻辑代码写在前台服务中

But!!!各厂商的系统不会轻易让你的app活在后台,会有各种限制,就很烦,就连无障碍服务都活不下去,前段时间Google还发起了针对无障碍服务被各大厂商系统杀死的投票。

cut-off

1、创建自己的前台服务类

创建一个类,使其继承 Service 类,并重写 onBind、onCreate、onDestroy 这三个方法。

代码块
clike
自动换行
复制代码
public class ForegroundService extends Service{
    //服务通信
    @Nullable
    @Override
    public IBinder onBind(Intent intent){
        //与Activity进行通信
        return null;
    }
    
    //服务创建时
    @Override
    public void onCreate(){
        super.onCreate();
        //服务创建时创建前台通知
        Notification notification = createForegroundNotification();
        //启动前台服务
        startForeground(1,notification);
		//有业务逻辑的代码可写在onCreate下
    }
    
    //服务销毁时
    @Override
    public void onDestroy(){
        //在服务被销毁时,关闭前台服务
        stopForeground(true);
        super.onDestroy();    
    }
    
    //创建前台通知,可写成方法体,也可单独写成一个类
    private Notification createForegroundNotification(){
        //前台通知的id名,任意
        String channelId = "ForegroundService";
        //前台通知的名称,任意
        String channelName = "Service";
        //发送通知的等级,此处为高,根据业务情况而定
        int importance = NotificationManager.IMPORTANCE_HIGH;
        //判断Android版本,不同的Android版本请求不一样,以下代码为官方写法
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(channelId,channelName,importance);
            channel.setLightColor(Color.BLUE);
            channel.setLockscreenVisiability(Notification.VISIBILITY_PRIVATE);
            NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);        
        }
        
        //点击通知时可进入的Activity
        Intent notificationIntent = new Intent(this,MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
        
        //最终创建的通知,以下代码为官方写法
        //注释部分是可扩展的参数,根据自己的功能需求添加
        return new NotificationCompat.Builder(this,channelId)
        	 .setContentTitle("填写通知的标题")
          	 .setContentText("填写通知的内容")
            .setSmallIcon(Icon)//通知显示的图标
            .setContentIntent(pendingIntent)//点击通知进入Activity
            .setTicker("通知的提示语")
            .build();
            //.setOngoing(true)
            //.setPriority(NotificationCompat.PRIORITY_MAX)
            //.setCategory(Notification.CATEGORY_TRANSPORT)
            //.setLargeIcon(Icon)
            //.setWhen(System.currentTimeMillis())
    }
}
复制成功

2、在清单文件中配置

声明前台服务权限

代码块
clike
自动换行
复制代码
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
复制成功

配置service

代码块
clike
自动换行
复制代码
<application>
    ......
    <service
        android:name=".ForegroundService"
        android:enabled="true"
        android:foregroundServiceType="location" />
</application>
复制成功

解释一下:

  1. 声明 <service> 需要放在 <application> ...... </application> 标签体中

  2. service 标签下第一个 name 就是我们创建的前台服务类,这里写你自己的类名,前面的点表示当前包名下

  3. enabled 表示是否启用

  4. foregroundServiceType 表示前台服务类型,这个参数很多人忘记写导致前台服务会被系统杀死

这样我们的前台服务就创建完成了,接下来在活动中去启动前台服务就可以了。

3、启动前台服务

以防万一,启动前台服务的代码放在 try-catch 中,防止出错使程序崩溃

代码块
clike
自动换行
复制代码
try{
    Intent intent = new Intent(this,ForegroundService.class);
    startForegroundService(intent);
}catch(Exception e){
    e.printStackTrace();
}
复制成功

这样我们的前台服务就完成了。

cut-off

Tip:如果想要使app活的更久怎么办?

目前我所知道的就是 前台服务 加上让用户手动去设置电池优化,把你的app设置为无限制,开启应用自启动。只要是用户隔三岔五的使用app就不会出现后台杀死的情况,如果一直放后台一两天用户没有把app切换到前台过,也有可能被杀死。

下一篇文章打算写一下如何保活无障碍服务,写法与前台服务类似,聪明的小伙伴是不是已经有思路了?

如果本篇文章对你有帮助,希望可以点赞+投币支持一下哦