can you give me a simple example of application with background service which uses bind/unbind methods to start and stop it? i was googling for it for an halfhour, but those examples uses startService/stopService methods or are very difficult for me. thank you.
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
Add these methods to your Activity:
And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.
Note, that when binding to a service only the
onCreate()
method is called in the service class. In your Service class you need to define the myBinder method:After you defined these methods you can reach the methods of your service at your Activity:
and finally you can start your service when some event occurs like _BOOT_COMPLETED_
note that when starting a service the
onCreate()
andonStartCommand()
is called in service class and you can stop your service when another event occurs by stopService() note that your event listener should be registerd in your Android manifest file:You can try using this code:
First of all, two things that we need to understand,
Client
bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), mServiceConn, Context.BIND_AUTO_CREATE);
here
mServiceConn
is instance ofServiceConnection
class(inbuilt) it is actually interface that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.Server
Now at client side, how to access all the methods of server?
IBinder
Object. So,IBinder
object is our handler which accesses all the methods ofService
by using (.) operator..
Now how to call method which lies in service
Here
myService
is object and serviceMethod is method in service. and by this way communication is established between client and server.