绑定到android中的同一个服务实例

发布于 2024-11-02 22:17:23 字数 3478 浏览 1 评论 0原文

我正在使用 MediaPlayer。我希望当用户离开活动时播放音乐。但是,当我离开并返回活动时,看起来我没有绑定到同一个实例。

这是我的代码:

public class MusicService extends Service {
        private NotificationManager mNM;

        public class LocalBinder extends Binder {
            MusicService getService() {
                return MusicService.this;
            }
        }

        @Override
        public void onCreate() {

        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
        }

        @Override
        public void onDestroy() {
            // Cancel the persistent notification.

            // Tell the user we stopped.
            Toast.makeText(this, "destroyed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }

        // This is the object that receives interactions from clients.  See
        // RemoteService for a more complete example.
        private final IBinder mBinder = new LocalBinder();

        public void showtoast(int i){
            Toast.makeText(this, "showtoast"+i, Toast.LENGTH_SHORT).show();
        }

        //Music player functions


        String path = "http://mp3stream";
        MediaPlayer mp;
        Boolean mpLoaded=false;
        public void play(){
            if(!mpLoaded){
                try {
                    mp=new MediaPlayer();
                    mp.setDataSource(path);
                    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mp.prepareAsync();
                    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                        public void onPrepared(MediaPlayer mp) {
                            mp.start();
                        }
                    });
                    mpLoaded=true;
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        public void pause(){
            if(mpLoaded){
                mp.stop();
                mpLoaded=false;
            }
        }
}

当我不离开活动时它工作得很好,但是当我离开活动并且音乐仍在播放时,当我返回并单击“停止”时,什么也没有发生。当我按下播放按钮时,另一个流开始。

调试器显示 mpLoaded 为 false,即使我可以听到该服务。

我就是这样绑定的。

private MusicService mBoundService;
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mBoundService = ((MusicService.LocalBinder)service).getService();
            mIsBound=true; 
            Toast.makeText(Main.this, "service connected", Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
            Toast.makeText(Main.this, "service disconnected", Toast.LENGTH_SHORT).show();
        }
    };

    void doBindService() {

        bindService(new Intent(getApplicationContext(), MusicService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }  

I'm playing around with the MediaPlayer. I want the music to play when the user leaves the activity. However when I leave and return to the activity it looks like I'm not binding to the same instance.

This is my code:

public class MusicService extends Service {
        private NotificationManager mNM;

        public class LocalBinder extends Binder {
            MusicService getService() {
                return MusicService.this;
            }
        }

        @Override
        public void onCreate() {

        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
        }

        @Override
        public void onDestroy() {
            // Cancel the persistent notification.

            // Tell the user we stopped.
            Toast.makeText(this, "destroyed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }

        // This is the object that receives interactions from clients.  See
        // RemoteService for a more complete example.
        private final IBinder mBinder = new LocalBinder();

        public void showtoast(int i){
            Toast.makeText(this, "showtoast"+i, Toast.LENGTH_SHORT).show();
        }

        //Music player functions


        String path = "http://mp3stream";
        MediaPlayer mp;
        Boolean mpLoaded=false;
        public void play(){
            if(!mpLoaded){
                try {
                    mp=new MediaPlayer();
                    mp.setDataSource(path);
                    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mp.prepareAsync();
                    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                        public void onPrepared(MediaPlayer mp) {
                            mp.start();
                        }
                    });
                    mpLoaded=true;
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        public void pause(){
            if(mpLoaded){
                mp.stop();
                mpLoaded=false;
            }
        }
}

It works just fine when I don't leave the activity, but when I do and the music is still playing, when I return and click stop, nothing happens. When I press the play button another stream is started.

The debugger shows that mpLoaded is false, even through I can hear the service.

This is how I bind it.

private MusicService mBoundService;
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mBoundService = ((MusicService.LocalBinder)service).getService();
            mIsBound=true; 
            Toast.makeText(Main.this, "service connected", Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
            Toast.makeText(Main.this, "service disconnected", Toast.LENGTH_SHORT).show();
        }
    };

    void doBindService() {

        bindService(new Intent(getApplicationContext(), MusicService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人九事 2024-11-09 22:17:23

您是否在关闭事件处理程序(例如 Activity 的 onStop)上解除与服务的绑定?如果是这样,该服务将被解除绑定并被销毁,您仍然可以听到音乐的唯一原因是 MediaPlayer 仍然处于活动状态。通过绑定服务,每次绑定然后取消绑定时,您都会获得一个新实例。

如果您想要持久服务实例,请使用 启动服务。服务的生命周期将独立于任何绑定活动,您可以调用 stopService 结束服务实例。

Are you unbinding from the service on a closing event handler such as onStop of your Activity? If so, the service is unbound and destroyed, and the only reason you're still hearing the music is because the MediaPlayer is still active. With bound services, you get a new instance every time you bind and then unbind.

If you want a persistent service instance, use startService. The service's life cycle will be independent of any binding activities, and you can call stopService to end the service instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文