我有處理手機連接,如果它斷開手柄耳機刷卡出最近使用的應用列表
這裏暫停媒體播放服務是代碼
private static int headsetSwitch = 1;
public static boolean headsetconnected = false;
public BroadcastReceiver headsetReciever = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent
.getAction())) {
// Pause the playback
mediaPlayer.pause();
}
if (intent.hasExtra("state")) {
if (headsetconnected && intent.getIntExtra("state", 0) == 0) {
headsetconnected = false;
Toast.makeText(getApplicationContext(),
"headsetconnected = false", Toast.LENGTH_SHORT)
.show();
headsetSwitch = 0;
}
else if (!headsetconnected
&& intent.getIntExtra("state", 0) == 1) {
headsetconnected = true;
Toast.makeText(getApplicationContext(),
"headsetconnected = true", Toast.LENGTH_SHORT)
.show();
headsetSwitch = 1;
// Lockscreencontrol();
}
}
switch (headsetSwitch) {
case (0):
headsetDisconnected();
break;
case (1):
break;
}
}
};
private void headsetDisconnected() {
try {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
if (PlayerActivity.play != null) {
PlayerActivity.play
.setImageResource(R.drawable.ic_play_arrow_white_36dp);
}
if (MainActivity.play != null) {
MainActivity.play
.setImageResource(R.drawable.ic_play_arrow_white_24dp);
}
if (getallsongs.play != null) {
getallsongs.play
.setImageResource(R.drawable.ic_play_arrow_white_24dp);
}
}
} catch (Exception e) {
}
}
此代碼的工作得很好,如果應用程序最小化和服務正在運行
如果我們從最近使用的應用列表刷卡應用程將出現問題
現指的這個https://stackoverflow.com/a/18618060/3126760
回答說:Don't ever swipe apps
但是這不是用戶
該應用程序的一般行爲只會崩潰,並嘗試重新啓動服務,並再次崩潰
我的問題是
我們如何管理這個特殊的生命週期事件,它既不由
ondestroy
在onpause
我們如何管理已經得到了在後臺運行的服務和應用程序已經被偷走了最近使用的應用列表
我見過的應用程序,其悄然關閉應用程序,一旦上述事件的應用程序發生
我們如何才能停止應用程序而不會崩潰。
我甚至試圖管理unregister listeners
當應用被刷出使用
<service
android:name="com.musicplayer.mp3player.PlayService"
android:enabled="true"
android:stopWithTask="false"
android:label="Audio-playback service" >
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
然後
公共無效onTaskRemoved(意向rootIntent){
// unregister listeners
// do any other cleanup if required
try {
unregisterReceiver(headsetReciever);
} catch (Exception e) {
// TODO: handle exception
}
// stop service stopSelf();
}
並呼籲stopForeground(true);
在ondestroy
導致這樣的問題。
請提供您可能提供的答案的解釋,謝謝。
你可以發佈一個StackTrace,你指的是_應用程序只會崩潰並嘗試重新啓動服務,並再次崩潰_ –