最近在做的專案中需要app在後臺常駐,用於實時上傳一些健康資訊資料,便於後臺實時檢視使用者的健康狀況。自從Android7.0以上後臺常駐實現越來越難,尤其是8.0及以上。關於保活的文章比比皆是,但是效果並不理想,關於保活的方法也就常說的哪幾種,重點在於怎麼組合運用。最終實現效果為:使用者不主動強制殺死的話,能夠一直存活(小米,華為,vivo,oppo,三星)。其中三星s8,華為nova2s使用者強制殺死也能存活。
專案結構
常見的保活方案
關於Android應用保活的文章很多,這裡不再闡述,可自行百度。重點在於運用這樣方案來實現保活功能。
程式碼實現
1.監聽鎖屏廣播,開啟1個畫素的Activity。
在鎖屏的時候啟動一個1個畫素的Activity,當使用者解鎖以後將這個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.雙程式守護
定義一個本地服務,在該服務中播放無聲音樂,並繫結遠端服務。
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?.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?.getTitle(), KeepLive.foregroundNotification?.getDescription(), KeepLive.foregroundNotification!!.getIconRes())
}
} catch (e: RemoteException) {
e.printStackTrace()
}
}
}
override fun onDestroy() {
super.onDestroy()
unbindService(connection)
if (KeepLive.keepLiveService != null) {
KeepLive.keepLiveService?.onStop()
}
}
}
複製程式碼
定義一個遠端服務,繫結本地服務。
class RemoteService : Service() {
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 {
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()?.foregroundNotificationClick(context, intent)
}
}
}
}
}
複製程式碼
3.JobScheduler
JobScheduler和JobService是安卓在api 21中增加的介面,用於在某些指定條件下執行後臺任務。
定義一個JobService,開啟本地服務和遠端服務
@SuppressWarnings(value = ["unchecked", "deprecation"])
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class JobHandlerService : JobService() {
private var mJobScheduler: JobScheduler? = null
override fun onStartCommand(intent: Intent?, 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?.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.播放無聲音樂
這裡使用的是有聲的mp3檔案,只是在程式碼中把聲音設定成了0;如果使用真正的無聲的音樂檔案,在oppo手機上按下返回鍵會被立刻殺死,並且在三星手機,華為nova2s強制殺死也會被殺死,所有使用了有聲的檔案。
5.提高Service優先順序
在onStartCommand()
方法中開啟一個通知,提高程式的優先順序。注意:從Android 8.0(API級別26)開始,所有通知必須要分配一個渠道,對於每個渠道,可以單獨設定視覺和聽覺行為。然後使用者可以在設定中修改這些設定,根據應用程式來決定哪些通知可以顯示或者隱藏。
定義一個通知工具類,相容8.0
class NotificationUtils(context: Context) : ContextWrapper(context) {
private var manager: NotificationManager? = null
private var id: String = context.packageName + "51"
private var name: String = context.packageName
private var context: Context = context
private var channel: NotificationChannel? = null
companion object {
@SuppressLint("StaticFieldLeak")
private var notificationUtils: NotificationUtils? = null
fun createNotification(context: Context, title: String, content: String, icon: Int, intent: Intent): Notification? {
if (notificationUtils == null) {
notificationUtils = NotificationUtils(context)
}
var notification: Notification? = null
notification = if (Build.VERSION.SDK_INT >= 26) {
notificationUtils?.createNotificationChannel()
notificationUtils?.getChannelNotification(title, content, icon, intent)?.build()
} else {
notificationUtils?.getNotification_25(title, content, icon, intent)?.build()
}
return notification
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
fun createNotificationChannel() {
if (channel == null) {
channel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_MIN)
channel?.enableLights(false)
channel?.enableVibration(false)
channel?.vibrationPattern = longArrayOf(0)
channel?.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)
}
}
複製程式碼
使用
將保活的功能封裝成了一個單獨的庫,依賴該庫即可。
app中使用:
KeepLive.startWork(this, KeepLive.RunMode.ROGUE, ForegroundNotification("Title", "message",
R.mipmap.ic_launcher, object : ForegroundNotificationClickListener {
override fun foregroundNotificationClick(context: Context, intent: Intent) {
//點選通知回撥
}
}), object : KeepLiveService {
override fun onStop() {
//可能呼叫多次,跟onWorking匹配呼叫
}
override fun onWorking() {
//一直存活,可能呼叫多次
}
})
複製程式碼
清單檔案配置:
<!--許可權配置-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.REORDER_TASKS" />
<!--保活相關配置-->
<receiver android:name="com.xiyang51.keeplive.receiver.NotificationClickReceiver" />
<activity android:name="com.xiyang51.keeplive.activity.OnePixelActivity" />
<service android:name="com.xiyang51.keeplive.service.LocalService" />
<service android:name="com.xiyang51.keeplive.service.HideForegroundService" />
<service
android:name="com.xiyang51.keeplive.service.JobHandlerService"
android:permission="android.permission.BIND_JOB_SERVICE" />
<service
android:name="com.xiyang51.keeplive.service.RemoteService"
android:process=":remote" />
複製程式碼