Communicate with foreground service android

前端 未结 2 1538
耶瑟儿~
耶瑟儿~ 2021-02-04 01:15

First question here, but I\'ve been around for a while.

What do I have:

I\'m building an Android app which plays audio streams and online playl

2条回答
  •  醉话见心
    2021-02-04 01:38

    No. bindService will not start a service . It will just bind to the Service with a service connection, so that you will have the instance of the service to access/control it.

    As per your requirement I hope you will have the instance of MediaPlayer in service . You can also start the service from Activity and then bind it. If the service is already running onStartCommand() will be called, and you can check if MediaPlayer instance is not null then simply return START_STICKY.

    Change you Activity like this..

    public class MainActivity extends ActionBarActivity {
    
        CustomService customService = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // start the service, even if already running no problem.
            startService(new Intent(this, CustomService.class));
            // bind to the service.
            bindService(new Intent(this,
              CustomService.class), mConnection, Context.BIND_AUTO_CREATE);
        }
    
        private ServiceConnection mConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                customService = ((CustomService.LocalBinder) iBinder).getInstance();
                // now you have the instance of service.
            }
    
            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                customService = null;
            }
        };
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (customService != null) {
                // Detach the service connection.
                unbindService(mConnection);
            }
        }
    }
    

    I have similar application with MediaPlayer service. let me know if this approach doesn't help you.

提交回复
热议问题