android 保活的一种有效的方法

android 保活的一种有效的方法

为什么要保活

说起程序的保活,其实很多人都觉得,要在手机上进行保活,确实是想做一些小动作,其实有些正常的场景也是需要我们进行保活的,这样可以增强我们的用户体验。保活就是使得程序常驻内存,这种程序不容易被杀,或者在被杀以后还能完成自我启动,相当于有个监控程序一样,当我们的程序退出以后,能帮我们在拉起来。

保活方式

保活的方式有很多,但是大部分的效果并不是很好,如果有看过其他的一些文章,我们应该有了解,双进程保活,一像素保活,so保活,关播保活等。

但是这些保活方式还是很容易被杀。根本无法对抗一些高级的查杀软件,或者是 adb shell am force-stop XXX

如果能够抗住force-stop 那么基本上也就能在内存上站住脚了。

应用通知保活

通过了那么多的试验后,发现应用通知保活 这种方式是最简单而且支持的厂商也最多。唯一的缺点就是需要用户开启权限。

如果有用过一些push消息以后,我们会发现这些push消息,能够推送到手机上,当我们点击提示的时候会调到我们的应用中,如果利用push的消息,发现手机和我们断开了,我们往手机里面发送一个push消息,是否可以把我们的应用拉起来?

在这里插入图片描述

下面把程序实现出来,看看他能不能过扛得住force-stop

新建一个 NotificationService

open class NotificationService : NotificationListenerService() {

    private val TAG = "NotificationService"


    override fun onCreate() {
        

        super.onCreate()
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return Service.START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return super.onBind(intent)
    }

    override fun onRebind(intent: Intent?) {
        super.onRebind(intent)
    }

    override fun onUnbind(intent: Intent?): Boolean {
        return super.onUnbind(intent)
    }

    override fun onListenerConnected() {
        super.onListenerConnected()
    }

    override fun onListenerDisconnected() {
        super.onListenerDisconnected()
    }

    override fun onNotificationRemoved(sbn: StatusBarNotification) {
        super.onNotificationRemoved(sbn)
    }

    override fun onNotificationPosted(sbn: StatusBarNotification) {
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}

NotificationService 是空的,我们这里不做什么事情,如果你想做一些启动其他服务的事情,你也可以在这里onCreate进行。

AndroidManifest.xml 中,加入 NotificationService 服务,注册这个服务到系统中。

        <service
            android:name=".service.NotificationService"
            android:exported="true"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter android:priority="999">
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>

就是这么简单,没有几行代码就可以实现一个保活的程序。我们看看效果如何?

记住一定要到设备和应用通知 把我们的程序打开来。

在这里插入图片描述
我们的demo程序为com.first66.keepmealive ,一开始的时候程序是活着的,我们需要制造一个意外让程序结束,这个意外我们直接用adb 命令来干掉com.first66.keepmealive

adb shell am force-stop com.first66.keepmealive

发现com.first66.keepmealive 先结束以后,后面马上又自己跑起来了。这个过程执行了两次,两次app都能够自己启动起来。

如果需要程序代码的话,可以和我进行私信联系。

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

go2coding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值