開(kāi)發(fā)背景:
需求:定時(shí)清理殺應(yīng)用,但是需要判斷用戶當(dāng)前是否在播放,如果在播放不能殺應(yīng)用(暫停狀態(tài)也屬于正在播放)
需要特別考慮三種狀態(tài):
1.無(wú)論是系統(tǒng)app播放,還是三方app播放,都不能清理;
2.無(wú)論是全屏播放,或者是小屏幕播放,都不能清理;
3.無(wú)論是播放還是暫停,都不能清理;
方法1:
通過(guò)AudioManager,判斷當(dāng)前設(shè)備是否正在占用聲音播放,來(lái)判斷是否正在播放;
缺點(diǎn)是:當(dāng)用戶點(diǎn)擊暫停后,是不占用Audio資源的,所以無(wú)法判斷暫停狀態(tài);
private boolean isPlaying() {
if (audioManager == null)
audioManager = (AudioManager) this.getSystemService(AUDIO_SERVICE);
Log.i(TAG, "audioManager.isMusicActive() = " + audioManager.isMusicActive());
Log.i(TAG, "audioManager.isLocalOrRemoteMusicActive() = " + audioManager.isLocalOrRemoteMusicActive());
if (audioManager.isMusicActive()) {
return true;
}
if (audioManager.isLocalOrRemoteMusicActive()) {
return true;
}
return false;
}
方法二:
hisi平臺(tái)在播放視頻資源時(shí),在proc/msp/vpss00節(jié)點(diǎn)會(huì)有視頻相關(guān)信息寫入;
通過(guò)讀取這個(gè)節(jié)點(diǎn),判斷當(dāng)前是否有視頻資源正在被占用;
優(yōu)點(diǎn):在視頻播放暫停狀態(tài)下可以有效判斷
private boolean isPlaying() {
if (AutoClearUtil.isVpss00Empty())
return false;
return true;
}
/**
* 讀取proc/msp/vpss00節(jié)點(diǎn)的信息
* 當(dāng)節(jié)點(diǎn)信息為空時(shí),播放器沒(méi)有使用
* 當(dāng)節(jié)點(diǎn)信息不為空,播放器正在使用
* @return
*/
public static boolean isVpss00Empty() {
Process catProcess = null;
BufferedReader mReader = null;
try {
catProcess = Runtime.getRuntime().exec("cat proc/msp/vpss00");
mReader = new BufferedReader(new InputStreamReader(
catProcess.getInputStream()), 1024);
String line = null;
if ((line = mReader.readLine()) != null) {
Log.i(TAG, "cat proc/msp/vpss00 = " + line);
return false;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (mReader != null)
mReader.close();
} catch (IOException e) {
e.printStackTrace();
}
if (catProcess != null)
catProcess.destroy();
}
return true;
}