我正在嘗試編寫MediaPlayer
附帶的服務。我有不同的活動訪問它,所以我認爲最好仔細閱讀一項服務。Android上的持續服務
它迄今爲止工作正常,我還添加了一個電話startForeground
,如here所述。通知顯示出來。
但是,當我現在按設備上的主頁或後退按鈕時,服務將停止並調用onDestroy
,並且通知圖標消失。當我回來時,服務似乎很好。
我停止音樂播放onDestroy
,所以它當然停止。但是,即使用戶使用其他應用程序,我也希望保持通知和服務的連貫性。
編輯:我希望這是相關部分:
public class MediaPlayerService extends Service {
private static class PlayerMessageHandler extends Handler {
private final MediaPlayerService owner;
public PlayerMessageHandler(MediaPlayerService owner) {
this.owner = owner;
}
@Override
public void handleMessage(Message msg) {
// Handle
}
}
private static final int NOTIFICATION_ID = 13138;
private final Messenger messenger = new Messenger(new PlayerMessageHandler(
this));
private MediaPlayer player;
private Notification notification;
@Override
public IBinder onBind(Intent intent) {
startNotification();
return messenger.getBinder();
}
@Override
public void onCreate() {
super.onCreate();
Log.v(TAG, "Media player service created.");
player = new AudiobookPlayer(this);
new Thread(seekerUpdate).start();
isRunning = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "Received start id " + startId + ": " + intent);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.v(TAG, "Media player service destroyed.");
if (player.isPlaying()) {
player.pause();
}
sendMessageToUI(MSG_PLAYER_HAS_PAUSED);
isRunning = false;
}
private void sendMessageToUI(int msg) {
Log.v(TAG, "Sending " + msg);
sendMessage(Message.obtain(null, msg));
}
private void sendMessage(final Message message) {
// Send
}
private void startNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
builder.setSmallIcon(R.drawable.notification);
builder.setContentTitle(getString(R.string.app_name));
notification = builder.build();
startForeground(NOTIFICATION_ID, notification);
}
}
EDIT2:從活動的方法,從here
@Override
protected void onStart() {
super.onStart();
// Bind to the service
bindService(new Intent(this, MediaPlayerService.class),
playerServiceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (bound) {
unbindService(playerServiceConnection);
bound = false;
}
}
對不起,但你的問題是什麼? – Bex
@Bex:問題在於,即使用戶在另一個應用程序中,我也可以使服務保持活躍狀態。 – Lanbo
我想,你需要一個Wakelock來讓服務持續下去 – flx