小编Mai*_*aik的帖子

服务不断被破坏

我有一项使用媒体播放器播放音乐的服务。该服务由一个活动启动,如果正在播放某些内容并且用户离开该活动,该服务应继续在后台播放。在前台运行服务似乎有效(我可以看到通知),但在几乎所有情况下,服务都会立即被销毁(服务上的系统调用 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)); …
Run Code Online (Sandbox Code Playgroud)

service lifecycle android

2
推荐指数
1
解决办法
7792
查看次数

标签 统计

android ×1

lifecycle ×1

service ×1