【问题标题】:Connect to Service after activity recreation活动娱乐后连接到服务
【发布时间】:2012-12-16 07:47:48
【问题描述】:

我有播放音乐的活动和服务。 onCreate 的活动我 startService 并尝试创建一个 ServiceConnection,在 ServiceConnection 的 onServiceConnected 中我初始化了服务,因此在此之后它不为空。然后我将服务绑定到这个服务连接。

所以,我的 musicService 不为空,应用程序正常工作,服务可以发送前台通知。假设我旋转了我的设备并旋转了屏幕,我的活动调用了 onDestroy 并调用了 onCreate。我的 musicService 继续播放,但是在 onCreate 中有 startService,再次创建 ServiceConnection 和 bindService,应用程序由于 null musicService 而崩溃。

我透露这是因为 ServiceConnection 的 onServiceConnected 现在从未调用过。 我应该怎么做才能连接到我在第一个活动启动音乐服务时创建的?

我的代码在每个 onCreate 上运行:

    Intent intent = new Intent(this, MusicPlaybackService.class);
    startService(intent);
    serviceConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            LocalBinder binder = (LocalBinder) service;
            musicPlaybackService = binder.getService(); 
        }

        public void onServiceDisconnected(ComponentName arg0) {
        }
    };
    bindService(intent, serviceConnection, 0);

【问题讨论】:

  • 添加代码。将使情况变得更容易
  • 完成了,但我不确定它是否让事情变得更容易,我认为我的描述已经很完整了。

标签: java android service android-activity


【解决方案1】:

我不知道我做了什么,但它有效。现在我有了这段代码。

    Intent intent = new Intent(this, MusicPlaybackService.class);
    MyApplication.getAppContext().startService(intent);
    serviceConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            LocalBinder binder = (LocalBinder) service;
            musicPlaybackService = binder.getService();
            // now onServiceConnected calls on screen rotation.
        }

        public void onServiceDisconnected(ComponentName arg0) {
        }
    };
    MyApplication.getAppContext().bindService(intent, serviceConnection, BIND_AUTO_CREATE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2015-11-17
    • 2011-08-12
    • 2021-03-13
    相关资源
    最近更新 更多