我正在尝试编写一个MediaPlayer附带的服务.我有不同的活动访问它,所以我认为最好仔细阅读服务.
它到目前为止工作正常,我还添加了对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;
}
}
解决方法:
public class HelloService extends Service {
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
// If we get killed, after returning from here, restart
return START_STICKY;
}
...
}
编辑:从之后的讨论中发现,我的怀疑是正确的,雨果提供了一个现场诊断.我想你现在需要添加builder.setOngoing(true);在startNotification()中.
标签:android,service,notifications
来源: https://codeday.me/bug/20190725/1533440.html