休眠
非Root環(huán)境
綠色守護(hù)在非Root的環(huán)境下,休眠使用的是通過(guò)無(wú)障礙服務(wù)(AccessibilityService)跳轉(zhuǎn)到應(yīng)用信息頁(yè)面自動(dòng)點(diǎn)擊強(qiáng)行停止實(shí)現(xiàn)的效拭。
Root環(huán)境
在Root環(huán)境下,休眠使用的是force-stop,在adb中可使用下面命令對(duì)進(jìn)程進(jìn)行休眠缎患。也可在代碼中執(zhí)行shell命令阎肝。
adb shell am force-stop <PACKAGE>
如果有App有系統(tǒng)簽名則可無(wú)需Root權(quán)限,通過(guò)代碼也可調(diào)用force-stop方法
//清單文件,該權(quán)限需要系統(tǒng)簽名
<uses-permission android:name="android.permission.FORCE_STOP_PACKAGES"/>
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val method: Method = Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", String::class.java)
method.invoke(activityManager, packageName)
智能休眠--檢測(cè)媒體播放狀態(tài)
綠色守護(hù)可在開(kāi)啟智能休眠后根據(jù)媒體播放狀態(tài)進(jìn)行過(guò)濾休眠蚂蕴。
申請(qǐng)?jiān)L問(wèn)通知權(quán)限
val notificationSettingIntent = Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
activity.startActivityForResult(notificationSettingIntent, requestCode)
創(chuàng)建NotificationListenerService
<service android:name=".service.NotificationMonitorService"
android:label="NotificationMonitor"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
//NotificationMonitorService.kt
class NotificationMonitorService : NotificationListenerService() {}
通過(guò)MediaSessionManager獲取當(dāng)前正在播放音頻的應(yīng)用
private fun getActiveSessionsPackageName(): String? {
val mediaSessionManager = App.context.getSystemService(Context.MEDIA_SESSION_SERVICE) as MediaSessionManager
val activeSessionsList = mediaSessionManager.getActiveSessions(
ComponentName(
App.context,
NotificationMonitorService::class.java
)
)
//Log.e(TAG, activeSessionsList.toString())
for (activeSessions in activeSessionsList) {
val currentState = activeSessions.playbackState?.state
if (currentState == PlaybackState.STATE_PLAYING) {
Log.e(TAG, "當(dāng)前正在播放音頻的包名:${activeSessions.packageName}")
return activeSessions.packageName
}
}
return null
}