Communicate With Foreground Service Android
Solution 1:
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..
publicclassMainActivityextendsActionBarActivity {
CustomService customService = null;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// start the service, even if already running no problem.startService(newIntent(this, CustomService.class));
// bind to the service.bindService(newIntent(this,
CustomService.class), mConnection, Context.BIND_AUTO_CREATE);
}
privateServiceConnection mConnection = newServiceConnection() {
@OverridepublicvoidonServiceConnected(ComponentName componentName, IBinder iBinder) {
customService = ((CustomService.LocalBinder) iBinder).getInstance();
// now you have the instance of service.
}
@OverridepublicvoidonServiceDisconnected(ComponentName componentName) {
customService = null;
}
};
@OverrideprotectedvoidonDestroy() {
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.
Solution 2:
Quoting Android documentation:
A bound service is destroyed once all clients unbind, unless the service was also started
And about the difference between started and bound just take a look to https://developer.android.com/guide/components/services.html
So, you have to create the Service using startService
and then bindService
, like @Libin does in his/her example. Then, the service will run until you use stopService
or stopSelf
or until Android decides that it needs resources and kills you.
Post a Comment for "Communicate With Foreground Service Android"