Android how do I wait until a service is actually connected?

前端 未结 7 1930
遇见更好的自我
遇见更好的自我 2020-12-02 12:50

I have an Activity calling a Service defined in IDownloaderService.aidl:

public class Downloader extends Activity {
 IDownloaderService downloader = null;
//         


        
7条回答
  •  无人及你
    2020-12-02 13:41

    I wanted to add some things you should or should not do:

    1. bind the service not on create but onResume and unbind it onPause. Your app can go into pause (background) at any time by user interaction or OS-Screens. Use a distinct try/catch for each and every service unbinding, receiver unregistering etc in onPause so if one is not bound or registered the exception doesn't prevent the others from being destroyed too.

    2. I usually capsule binding in a public MyServiceBinder getService() Method. I also always use a blocking boolean variable so I don't have to keep an eye on all those calls using the servie in the activity.

    Example:

    boolean isBindingOngoing = false;
    MyService.Binder serviceHelp = null;
    ServiceConnection myServiceCon = null;
    
    public MyService.Binder getMyService()
    {
       if(serviceHelp==null)
       {
           //don't bind multiple times
           //guard against getting null on fist getMyService calls!
           if(isBindingOngoing)return null; 
           isBindingOngoing = true;
           myServiceCon = new ServiceConnection(
               public void onServiceConnected(ComponentName cName, IBinder binder) {
                   serviceHelp = (MyService.Binder) binder;
                   //or using aidl: serviceHelp = MyService.Stub.AsInterface(binder);
                   isServiceBindingOngoing = false;
                   continueAfterServiceConnect(); //I use a method like this to continue
               }
    
               public void onServiceDisconnected(ComponentName className) {
                  serviceHelp = null;
               }
           );
           bindService(serviceStartIntent,myServiceCon);
       }
       return serviceHelp;
    }
    

提交回复
热议问题