服务不断被破坏

时间:2014-04-06 13:57:04

标签: android service lifecycle

我有一项使用媒体播放器播放音乐的服务。该服务由活动启动,如果正在播放某些内容且用户离开活动,则该服务应继续在后台播放。 在前台运行服务似乎工作(我可以看到通知),但在接近所有情况下,服务立即被销毁(OnDestroy由服务上的系统调用)。 我知道使用startForeground并不意味着该服务永远不会被杀死,但它会立即被破坏,所以我认为太少的资源迫使系统杀死它,这不是原因。

这就是我实现它的方式: 在活动的OnCreate中,我启动(在后台)并绑定服务。在OnPause中,我将服务带到前台也不会被破坏:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);

    // start service
    startService(new Intent(this, MyService.class));
    // connect to service
    bindToService();
    ...
}

@Override
protected void onDestroy() {
    unbindFromService();
    super.onDestroy();
};

@Override
protected void onStart() {
    super.onStart();
}

@Override
protected void onStop() {
    super.onStop();
}

@Override
protected void onPause() {
    super.onPause();

    if (MediaPlayerService.getInstance().getStatus() == MEDIA_PLAYER_STATUS.Started) {
        // current playing something => keep service running
        mService.startForeground();
    } else {
        // stop service
        stopService(new Intent(MainActivity.this, MyService.class));
    }
}

@Override
protected void onResume() {
    super.onResume();

    // remove service from foreground
    if (mService != null) {
        mService.stopForeground();
    }
}

void bindToService() {
    // Establish a connection with the service. We use an explicit
    // class name because we want a specific service implementation that
    // we know will be running in our own process (and thus won't be
    // supporting component replacement by other applications).
    bindService(new Intent(MainActivity.this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

void unbindFromService() {
    if (mIsBound) {
        // Detach our existing connection.
        unbindService(mConnection);
        mIsBound = false;
    }
}

private final ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        // This is called when the connection with the service has been
        // established, giving us the service object we can use to
        // interact with the service. Because we have bound to a explicit
        // service that we know is running in our own process, we can
        // cast its IBinder to a concrete class and directly access it.
        mService = ((MyService.LocalBinder) service).getService();
        mService.registerClient(MainActivity.this);
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        // Because it is running in our same process, we should never
        // see this happen.
        mService = null;
        mService.unRegisterClient(MainActivity.this);
    }
};

我的服务中的start / stopForeground函数如下所示:

public void startForeground() {
    String songName = "blabla";
    // assign the song name to songName
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
            new Intent(getApplicationContext(), MainActivity.class),
            PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification();
    notification.tickerText = songName;
    notification.icon = R.drawable.ic_launcher;
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notification.setLatestEventInfo(getApplicationContext(), "MusicPlayerSample",
            "Playing: " + songName, pi);
    startForeground(NOTIFICATION_ID, notification);
}

public void stopForeground() {
    stopForeground(true);
}

如果我离开活动,服务会不断被破坏的任何想法?

2 个答案:

答案 0 :(得分:3)

这是您的answer

  

只要绑定了另一个应用程序组件,绑定服务就会运行。多个组件可以立即绑定到服务,但是当所有组件解除绑定时,服务将被销毁。

您应该致电startService()

答案 1 :(得分:3)

问题是onCreate / onDestroy中的bind / unbind。 我无法解释它,但是在生命周期状态中绑定会导致服务被破坏,即使您在活动的onCreate()中使用了startService()。

此设置现在可以正常使用:

  • 在activity的onCreate()中使用startService()来启动服务。
  • 服务的onStartCommand()必须返回Service.START_STICKY
  • 在Activity的onResume()绑定到服务
  • 在Activity的onPause()中,如果正在播放某些内容,请调用该服务的startForeground()并从中取消绑定。
  • 如果当前没有任何内容正在播放,则在Activity的onDestroy()中调用stopService()。