App保活

本文介绍了一种通过两个Service相互绑定及监听链接状态来实现应用保活的方法。具体包括使用广播启动Service、在Service中进行相互绑定及启动,并通过Notification提高Service优先级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

查看App是否保活成功:https://my.oschina.net/huiyun/blog/1476143

主要思路: 主要是两个service的相互绑定,以及对链接状态的监听,一旦断开就重新启动和绑定。

  1. 通过Activity发送一个广播(OneReceiver),通过广播OneReceiver启动一个Service(MyService)
  2. 在MyService的onCreate()方法中初始化链接监听类【在Service里写一个类继承接口ServiceConnection,并在方法onServiceDisconnected()中启动OtherService并且与之绑定】
    
  3.  在MyService的onStartCommand()方法绑定OtherService,并写一个Notification,用startForeground()方法启动在通知栏,即提高该Service的优先级。
    
  4.  再创建一个OtherService(就是之前提到的),逻辑与MyService相同,唯一的不同就是在AndroidManifest.xml文件中注册时应将该服务现在另外的进程中,防止该App被kill时连带着OtherService也被kill,这样就无法实现相互唤醒了。
    

下面是主要的代码: MainActivity的代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendBroadcast(new Intent(this,MyReceiver.class));
    }
}

MyReceiver的代码:

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intent1 = new Intent(context,MyService.class);
        context.startService(intent1);
    }
}

MyService的代码:

public class MyService extends Service {
    private MyServiceConnection connection;
    private MyBinder binder;
    private PendingIntent pendingIntent;

    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        connection = new MyServiceConnection();
        if (binder == null) {
            binder = new MyBinder();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startService(new Intent(MyService.this, OtherService.class));
        bindService(new Intent(MyService.this, OtherService.class), connection, Context.BIND_IMPORTANT);
        //根据具体的项目需求改判断,这里假设是判断App是否
        if (isAppRunning()) {
            Intent main = new Intent(MyService.this,MainActivity.class);
            startActivity(main);
        }
        intent = new Intent(MyService.this, OtherReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(MyService.this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(MyService.this)
                .setContentTitle("MyService提示:")
                .setContentText("MyService 的内容。。。。")
                .setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .build();
        startForeground(startId, notification);
        return START_STICKY;
    }

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

    class MyBinder extends Binder {
    }

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("SaveApp", "MyServiceConnection : Connected");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("SaveApp", "MyServiceConnection : Disconnected");
            MyService.this.startService(new Intent(MyService.this,OtherService.class));
            MyService.this.bindService(new Intent(MyService.this,OtherService.class),connection,Context.BIND_IMPORTANT);
        }
    }

    public boolean isAppRunning() {
        ActivityManager am = (ActivityManager) getApplication().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals("demo.jhc.cn.jpush") && info.baseActivity.getPackageName().equals("demo.jhc.cn.jpush")) {
                return true;
            }
        }
        return false;
    }
}

OtherService的代码:

public class OtherService extends Service {
    private OtherBinder binder;
    private OtherServiceConnection connection;
    private PendingIntent pendingIntent;

    public OtherService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        connection = new OtherServiceConnection();
        if (binder == null) {
            binder = new OtherBinder();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bindService(new Intent(OtherService.this, MyService.class), connection, Context.BIND_IMPORTANT);
        if (isAppRunning()) {
            intent = new Intent(OtherService.this, MainActivity.class);
        }
        pendingIntent = PendingIntent.getBroadcast(OtherService.this, 0, intent, 0);
        Notification notification = new NotificationCompat
                .Builder(this)
                .setContentTitle("OtherService title")
                .setContentText("OtherService content")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build();
        notification.flags |=  Notification.FLAG_NO_CLEAR;
        startForeground(startId, notification);
        return START_STICKY;
    }

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

    class OtherBinder extends Binder {
    }

    class OtherServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("SaveApp", "MyServiceConnection : Connected");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("SaveApp", "MyServiceConnection : Disconnected");
            OtherService.this.startService(new Intent(OtherService.this,MyService.class));
            OtherService.this.bindService(new Intent(OtherService.this,MyService.class),connection,Context.BIND_IMPORTANT);
        }
    }

OtherReceiver的代码:

public class OtherReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"Other Receiver : 模拟Jpush接收器",Toast.LENGTH_SHORT).show();
    }
}

转载于:https://my.oschina.net/huiyun/blog/1476079

### Android 10 应用程序跃策略和技术 为了确应用程序在 Android 10 上能够持续运行并避免被系统回收,可以采用多种技术和最佳实践。这些技术不仅有助于提高应用性能,还能优化资源管理。 #### 使用前台服务 前台服务是一种特殊的服务类型,在执行重要操作时会显示通知给用户。这种方式可以让操作系统知道该进程非常重要,不应轻易终止它[^4]。 ```java Intent intent = new Intent(this, MyService.class); startForegroundService(intent); ``` #### 启动 sticky 服务 通过设置 `START_STICKY` 或者 `START_REDELIVER_INTENT` 标志来启动服务。当系统因内存不足而杀死此服务后,会在条件允许的情况下重新创建这个服务,并传递之前未完成的任务数据。 ```java @Override public int onStartCommand(Intent intent, int flags, int startId) { // Handle command here... return START_STICKY; } ``` #### 利用 JobScheduler API 对于需要定期执行后台任务的应用来说,JobScheduler 是一种更高效的选择。它可以安排网络请求或其他耗电工作只在网络可用或充电状下进行,从而减少电池消耗。 ```java ComponentName componentName = new ComponentName(context, MyJobService.class); JobInfo jobInfo = new JobInfo.Builder(0, componentName) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) .build(); JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); scheduler.schedule(jobInfo); ``` #### 配置唤醒锁(WakeLock) 如果某些情况下确实需要长时间持有 CPU 资源,则可以通过 PowerManager 的 WakeLock 接口获取部分类型的唤醒锁定权限。不过需要注意的是过度使用可能会显著影响设备续航时间。 ```java PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag"); wakeLock.acquire(); // Do work that requires CPU to stay on. wakeLock.release(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值