热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

详解Android8.0以上系统应用如何保活

这篇文章主要介绍了详解Android8.0以上系统应用如何保活,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

最近在做一个埋点的sdk,由于埋点是分批上传的,不是每次都上传,所以会有个进程保活的机制,这也是自研推送的实现技术之一:如何保证Android进程的存活。

对于Android来说,保活主要有以下一些方法:

  • 开启前台Service(效果好,推荐)
  • Service中循环播放一段无声音频(效果较好,但耗电量高,谨慎使用)
  • 双进程守护(Android 5.0前有效)
  • JobScheduler(Android 5.0后引入,8.0后失效)
  • 1 像素activity保活方案(不推荐)
  • 广播锁屏、自定义锁屏(不推荐)
  • 第三方推送SDK唤醒(效果好,缺点是第三方接入)

下面是具体的实现方案:

1.监听锁屏广播,开启1个像素的Activity

最早见到这种方案的时候是2015年,有个FM的app为了向投资人展示月活,在Android应用中开启一个1像素的Activity。

由于Activity的级别是比较高的,所以开启1个像素的Activity的方式就可以保证进程是不容易被杀掉的。

具体来说,定义一个1像素的Activity,在该Activity中动态注册自定义的广播。

class OnePixelActivity : AppCompatActivity() {

  private lateinit var br: BroadcastReceiver

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //设定一像素的activity
    val window = window
    window.setGravity(Gravity.LEFT or Gravity.TOP)
    val params = window.attributes
    params.x = 0
    params.y = 0
    params.height = 1
    params.width = 1
    window.attributes = params
    //在一像素activity里注册广播接受者  接受到广播结束掉一像素
    br = object : BroadcastReceiver() {
      override fun onReceive(context: Context, intent: Intent) {
        finish()
      }
    }
    registerReceiver(br, IntentFilter("finish activity"))
    checkScreenOn()
  }

  override fun onResume() {
    super.onResume()
    checkScreenOn()
  }

  override fun onDestroy() {
    try {
      //销毁的时候解锁广播
      unregisterReceiver(br)
    } catch (e: IllegalArgumentException) {
    }
    super.onDestroy()
  }

  /**
   * 检查屏幕是否点亮
   */
  private fun checkScreenOn() {
    val pm = this@OnePixelActivity.getSystemService(Context.POWER_SERVICE) as PowerManager
    val isScreenOn = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
      pm.isInteractive
    } else {
      pm.isScreenOn
    }
    if (isScreenOn) {
      finish()
    }
  }
}

2, 双进程守护

双进程守护,在Android 5.0前是有效的,5.0之后就不行了。首先,我们定义定义一个本地服务,在该服务中播放无声音乐,并绑定远程服务

class LocalService : Service() {
  private var mediaPlayer: MediaPlayer? = null
  private var mBilder: MyBilder? = null

  override fun onCreate() {
    super.onCreate()
    if (mBilder == null) {
      mBilder = MyBilder()
    }
  }

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

  override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    //播放无声音乐
    if (mediaPlayer == null) {
      mediaPlayer = MediaPlayer.create(this, R.raw.novioce)
      //声音设置为0
      mediaPlayer?.setVolume(0f, 0f)
      mediaPlayer?.isLooping = true//循环播放
      play()
    }
    //启用前台服务,提升优先级
    if (KeepLive.foregroundNotification != null) {
      val intent2 = Intent(applicationContext, NotificationClickReceiver::class.java)
      intent2.action = NotificationClickReceiver.CLICK_NOTIFICATION
      val notification = NotificationUtils.createNotification(this, KeepLive.foregroundNotification!!.getTitle(), KeepLive.foregroundNotification!!.getDescription(), KeepLive.foregroundNotification!!.getIconRes(), intent2)
      startForeground(13691, notification)
    }
    //绑定守护进程
    try {
      val intent3 = Intent(this, RemoteService::class.java)
      this.bindService(intent3, connection, Context.BIND_ABOVE_CLIENT)
    } catch (e: Exception) {
    }

    //隐藏服务通知
    try {
      if (Build.VERSION.SDK_INT <25) {
        startService(Intent(this, HideForegroundService::class.java))
      }
    } catch (e: Exception) {
    }

    if (KeepLive.keepLiveService != null) {
      KeepLive.keepLiveService!!.onWorking()
    }
    return Service.START_STICKY
  }

  private fun play() {
    if (mediaPlayer != null && !mediaPlayer!!.isPlaying) {
      mediaPlayer&#63;.start()
    }
  }

  private inner class MyBilder : GuardAidl.Stub() {

    @Throws(RemoteException::class)
    override fun wakeUp(title: String, discription: String, iconRes: Int) {

    }
  }

  private val cOnnection= object : ServiceConnection {

    override fun onServiceDisconnected(name: ComponentName) {
      val remoteService = Intent(this@LocalService,
          RemoteService::class.java)
      this@LocalService.startService(remoteService)
      val intent = Intent(this@LocalService, RemoteService::class.java)
      this@LocalService.bindService(intent, this,
          Context.BIND_ABOVE_CLIENT)
    }

    override fun onServiceConnected(name: ComponentName, service: IBinder) {
      try {
        if (mBilder != null && KeepLive.foregroundNotification != null) {
          val guardAidl = GuardAidl.Stub.asInterface(service)
          guardAidl.wakeUp(KeepLive.foregroundNotification&#63;.getTitle(), KeepLive.foregroundNotification&#63;.getDescription(), KeepLive.foregroundNotification!!.getIconRes())
        }
      } catch (e: RemoteException) {
        e.printStackTrace()
      }

    }
  }

  override fun onDestroy() {
    super.onDestroy()
    unbindService(connection)
    if (KeepLive.keepLiveService != null) {
      KeepLive.keepLiveService&#63;.onStop()
    }
  }
}

然后再定义一个远程服务,绑定本地服务。

class RemoteService : Service() {

  private var mBilder: MyBilder&#63; = null

  override fun onCreate() {
    super.onCreate()
    if (mBilder == null) {
      mBilder = MyBilder()
    }
  }

  override fun onBind(intent: Intent): IBinder&#63; {
    return mBilder
  }

  override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    try {
      this.bindService(Intent(this@RemoteService, LocalService::class.java),
          connection, Context.BIND_ABOVE_CLIENT)
    } catch (e: Exception) {
    }
    return Service.START_STICKY
  }

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

  private inner class MyBilder : GuardAidl.Stub() {
    @Throws(RemoteException::class)
    override fun wakeUp(title: String, discription: String, iconRes: Int) {
      if (Build.VERSION.SDK_INT <25) {
        val intent = Intent(applicationContext, NotificationClickReceiver::class.java)
        intent.action = NotificationClickReceiver.CLICK_NOTIFICATION
        val notification = NotificationUtils.createNotification(this@RemoteService, title, discription, iconRes, intent)
        this@RemoteService.startForeground(13691, notification)
      }
    }
  }

  private val cOnnection= object : ServiceConnection {
    override fun onServiceDisconnected(name: ComponentName) {
      val remoteService = Intent(this@RemoteService,
          LocalService::class.java)
      this@RemoteService.startService(remoteService)
      this@RemoteService.bindService(Intent(this@RemoteService,
          LocalService::class.java), this, Context.BIND_ABOVE_CLIENT)
    }

    override fun onServiceConnected(name: ComponentName, service: IBinder) {}
  }

}

/**
 * 通知栏点击广播接受者
 */
class NotificationClickReceiver : BroadcastReceiver() {

  companion object {
    const val CLICK_NOTIFICATION = "CLICK_NOTIFICATION"
  }

  override fun onReceive(context: Context, intent: Intent) {
    if (intent.action == NotificationClickReceiver.CLICK_NOTIFICATION) {
      if (KeepLive.foregroundNotification != null) {
        if (KeepLive.foregroundNotification!!.getForegroundNotificationClickListener() != null) {
          KeepLive.foregroundNotification!!.getForegroundNotificationClickListener()&#63;.foregroundNotificationClick(context, intent)
        }
      }
    }
  }
}

3,JobScheduler

JobScheduler是Android从5.0增加的支持一种特殊的任务调度机制,可以用它来实现进程保活,不过在Android8.0系统中,此种方法也失效。

首先,我们定义一个JobService,开启本地服务和远程服务。

@SuppressWarnings(value = ["unchecked", "deprecation"])
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class JobHandlerService : JobService() {

  private var mJobScheduler: JobScheduler&#63; = null

  override fun onStartCommand(intent: Intent&#63;, flags: Int, startId: Int): Int {
    var startId = startId
    startService(this)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      mJobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
      val builder = JobInfo.Builder(startId++,
          ComponentName(packageName, JobHandlerService::class.java.name))
      if (Build.VERSION.SDK_INT >= 24) {
        builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS) //执行的最小延迟时间
        builder.setOverrideDeadline(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS) //执行的最长延时时间
        builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS)
        builder.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR)//线性重试方案
      } else {
        builder.setPeriodic(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS)
      }
      builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
      builder.setRequiresCharging(true) // 当插入充电器,执行该任务
      mJobScheduler&#63;.schedule(builder.build())
    }
    return Service.START_STICKY
  }

  private fun startService(context: Context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      if (KeepLive.foregroundNotification != null) {
        val intent = Intent(applicationContext, NotificationClickReceiver::class.java)
        intent.action = NotificationClickReceiver.CLICK_NOTIFICATION
        val notification = NotificationUtils.createNotification(this, KeepLive.foregroundNotification!!.getTitle(), KeepLive.foregroundNotification!!.getDescription(), KeepLive.foregroundNotification!!.getIconRes(), intent)
        startForeground(13691, notification)
      }
    }
    //启动本地服务
    val localIntent = Intent(context, LocalService::class.java)
    //启动守护进程
    val guardIntent = Intent(context, RemoteService::class.java)
    startService(localIntent)
    startService(guardIntent)
  }

  override fun onStartJob(jobParameters: JobParameters): Boolean {
    if (!isServiceRunning(applicationContext, "com.xiyang51.keeplive.service.LocalService") || !isServiceRunning(applicationContext, "$packageName:remote")) {
      startService(this)
    }
    return false
  }

  override fun onStopJob(jobParameters: JobParameters): Boolean {
    if (!isServiceRunning(applicationContext, "com.xiyang51.keeplive.service.LocalService") || !isServiceRunning(applicationContext, "$packageName:remote")) {
      startService(this)
    }
    return false
  }

  private fun isServiceRunning(ctx: Context, className: String): Boolean {
    var isRunning = false
    val activityManager = ctx
        .getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val servicesList = activityManager
        .getRunningServices(Integer.MAX_VALUE)
    val l = servicesList.iterator()
    while (l.hasNext()) {
      val si = l.next()
      if (className == si.service.className) {
        isRunning = true
      }
    }
    return isRunning
  }
}

4,提高Service优先级

在onStartCommand()方法中开启一个通知,提高进程的优先级。注意:从Android 8.0(API级别26)开始,所有通知必须要分配一个渠道,对于每个渠道,可以单独设置视觉和听觉行为。然后用户可以在设置中修改这些设置,根据应用程序来决定哪些通知可以显示或者隐藏。

首先,定义一个通知工具类,此工具栏兼容Android 8.0。

class NotificationUtils(context: Context) : ContextWrapper(context) {

  private var manager: NotificationManager&#63; = null
  private var id: String = context.packageName + "51"
  private var name: String = context.packageName
  private var context: COntext= context
  private var channel: NotificationChannel&#63; = null

  companion object {
    @SuppressLint("StaticFieldLeak")
    private var notificationUtils: NotificationUtils&#63; = null

    fun createNotification(context: Context, title: String, content: String, icon: Int, intent: Intent): Notification&#63; {
      if (notificatiOnUtils== null) {
        notificatiOnUtils= NotificationUtils(context)
      }
      var notification: Notification&#63; = null
      notification = if (Build.VERSION.SDK_INT >= 26) {
        notificationUtils&#63;.createNotificationChannel()
        notificationUtils&#63;.getChannelNotification(title, content, icon, intent)&#63;.build()
      } else {
        notificationUtils&#63;.getNotification_25(title, content, icon, intent)&#63;.build()
      }
      return notification
    }
  }

  @RequiresApi(api = Build.VERSION_CODES.O)
  fun createNotificationChannel() {
    if (channel == null) {
      channel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_MIN)
      channel&#63;.enableLights(false)
      channel&#63;.enableVibration(false)
      channel&#63;.vibratiOnPattern= longArrayOf(0)
      channel&#63;.setSound(null, null)
      getManager().createNotificationChannel(channel)
    }
  }

  private fun getManager(): NotificationManager {
    if (manager == null) {
      manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    }
    return manager!!
  }

  @RequiresApi(api = Build.VERSION_CODES.O)
  fun getChannelNotification(title: String, content: String, icon: Int, intent: Intent): Notification.Builder {
    //PendingIntent.FLAG_UPDATE_CURRENT 这个类型才能传值
    val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    return Notification.Builder(context, id)
        .setContentTitle(title)
        .setContentText(content)
        .setSmallIcon(icon)
        .setAutoCancel(true)
        .setContentIntent(pendingIntent)
  }

  fun getNotification_25(title: String, content: String, icon: Int, intent: Intent): NotificationCompat.Builder {
    val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    return NotificationCompat.Builder(context, id)
        .setContentTitle(title)
        .setContentText(content)
        .setSmallIcon(icon)
        .setAutoCancel(true)
        .setVibrate(longArrayOf(0))
        .setSound(null)
        .setLights(0, 0, 0)
        .setContentIntent(pendingIntent)
  }
}

5,Workmanager方式

Workmanager是Android JetPac中的一个API,借助Workmanager,我们可以用它来实现应用饿保活。使用前,我们需要依赖Workmanager库,如下:

implementation "android.arch.work:work-runtime:1.0.0-alpha06"

Worker是一个抽象类,用来指定需要执行的具体任务。

public class KeepLiveWork extends Worker {
  private static final String TAG = "KeepLiveWork";

  @NonNull
  @Override
  public WorkerResult doWork() {
    Log.d(TAG, "keep-> doWork: startKeepService");
    //启动job服务
    startJobService();
    //启动相互绑定的服务
    startKeepService();
    return WorkerResult.SUCCESS;
  }
}

然后,启动keepWork方法,

  public void startKeepWork() {
    WorkManager.getInstance().cancelAllWorkByTag(TAG_KEEP_WORK);
    Log.d(TAG, "keep-> dowork startKeepWork");
    OneTimeWorkRequest OneTimeWorkRequest= new OneTimeWorkRequest.Builder(KeepLiveWork.class)
        .setBackoffCriteria(BackoffPolicy.LINEAR, 5, TimeUnit.SECONDS)
        .addTag(TAG_KEEP_WORK)
        .build();
    WorkManager.getInstance().enqueue(oneTimeWorkRequest);

  }

关于WorkManager,可以通过下面的文章来详细了解:WorkManager浅谈

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
  • 国内BI工具迎战国际巨头Tableau,稳步崛起
    尽管商业智能(BI)工具在中国的普及程度尚不及国际市场,但近年来,随着本土企业的持续创新和市场推广,国内主流BI工具正逐渐崭露头角。面对国际品牌如Tableau的强大竞争,国内BI工具通过不断优化产品和技术,赢得了越来越多用户的认可。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 本文将详细介绍如何使用剪映应用中的镜像功能,帮助用户轻松实现视频的镜像效果。通过简单的步骤,您可以快速掌握这一实用技巧。 ... [详细]
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 本文介绍如何在 Xcode 中使用快捷键和菜单命令对多行代码进行缩进,包括右缩进和左缩进的具体操作方法。 ... [详细]
  • 本文介绍了一款用于自动化部署 Linux 服务的 Bash 脚本。该脚本不仅涵盖了基本的文件复制和目录创建,还处理了系统服务的配置和启动,确保在多种 Linux 发行版上都能顺利运行。 ... [详细]
  • 在Linux系统中配置并启动ActiveMQ
    本文详细介绍了如何在Linux环境中安装和配置ActiveMQ,包括端口开放及防火墙设置。通过本文,您可以掌握完整的ActiveMQ部署流程,确保其在网络环境中正常运行。 ... [详细]
  • Android 渐变圆环加载控件实现
    本文介绍了如何在 Android 中创建一个自定义的渐变圆环加载控件,该控件已在多个知名应用中使用。我们将详细探讨其工作原理和实现方法。 ... [详细]
  • 如何在WPS Office for Mac中调整Word文档的文字排列方向
    本文将详细介绍如何使用最新版WPS Office for Mac调整Word文档中的文字排列方向。通过这些步骤,用户可以轻松更改文本的水平或垂直排列方式,以满足不同的排版需求。 ... [详细]
  • 本文总结了在使用Ionic 5进行Android平台APK打包时遇到的问题,特别是针对QRScanner插件的改造。通过详细分析和提供具体的解决方法,帮助开发者顺利打包并优化应用性能。 ... [详细]
  • 理解存储器的层次结构有助于程序员优化程序性能,通过合理安排数据在不同层级的存储位置,提升CPU的数据访问速度。本文详细探讨了静态随机访问存储器(SRAM)和动态随机访问存储器(DRAM)的工作原理及其应用场景,并介绍了存储器模块中的数据存取过程及局部性原理。 ... [详细]
  • 360SRC安全应急响应:从漏洞提交到修复的全过程
    本文详细介绍了360SRC平台处理一起关键安全事件的过程,涵盖从漏洞提交、验证、排查到最终修复的各个环节。通过这一案例,展示了360在安全应急响应方面的专业能力和严谨态度。 ... [详细]
  • 几何画板展示电场线与等势面的交互关系
    几何画板是一款功能强大的物理教学软件,具备丰富的绘图和度量工具。它不仅能够模拟物理实验过程,还能通过定量分析揭示物理现象背后的规律,尤其适用于难以在实际实验中展示的内容。本文将介绍如何使用几何画板演示电场线与等势面之间的关系。 ... [详细]
  • 本文介绍如何通过Windows批处理脚本定期检查并重启Java应用程序,确保其持续稳定运行。脚本每30分钟检查一次,并在需要时重启Java程序。同时,它会将任务结果发送到Redis。 ... [详细]
  • MySQL中枚举类型的所有可能值获取方法
    本文介绍了一种在MySQL数据库中查询枚举(ENUM)类型字段所有可能取值的方法,帮助开发者更好地理解和利用这一数据类型。 ... [详细]
author-avatar
陈杰铭雅意
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有