How do I bind this service in Android?

前端 未结 3 710
小鲜肉
小鲜肉 2020-12-06 02:36

This is the code in my Activity. Initiate an Intent, then a Connection, right?

hello_service = new Intent(this         


        
相关标签:
3条回答
  • 2020-12-06 02:54

    I would like to point out that if you follow the service examples provided by google then your service will leak memory, see this chaps excellent post on how to do it properly (and vote for the related Google bug)

    http://www.ozdroid.com/#!BLOG/2010/12/19/How_to_make_a_local_Service_and_bind_to_it_in_Android

    0 讨论(0)
  • 2020-12-06 02:56

    Binding to a service from an Activity should be avoided as it causes probems when the Activity Configurations change (e.g. if the device is rotated the activity would get created again from scratch and the binding would have to be re-created).
    Please refer to the comment from Commonsware on the following post on stackoverflow
    Communicate with Activity from Service (LocalService) - Android Best Practices

    0 讨论(0)
  • 2020-12-06 02:58

    To connect a service to an activity, all you need to write in a ServiceConnection implementation is :

    @Override
    public void onServiceDisconnected(ComponentName name) {
    mServiceBound = false;
    }
    
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
    MyBinder myBinder = (MyBinder) service;
    mBoundService = myBinder.getService();
    mServiceBound = true;
    }
    

    Here mBoundService is an object of your bound service. Have a look at this Bound Service Example.

    0 讨论(0)
提交回复
热议问题