Good practices for services on Android

前端 未结 3 1219
清酒与你
清酒与你 2021-01-23 05:05

I am currently using 2 services in my app:

1: LocationService, basically trying to localize the user, and aims to stay alive only when the app is on for

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 05:32

    It hasn't been well-documented in Google's official dev guide, Context.bindService() is actually an asynchronous call. This is the reason why ServiceConnection.onServiceConnected() is used as a callback method, means not happened immediately.

    public class MyActivity extends Activity {
      private MyServiceBinder myServiceBinder;
    
      protected ServiceConnection myServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
          myServiceBinder = (MyServiceBinderImpl) service;
        }
    
        ... ...
      }
    
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // bindService() is an asynchronous call. myServiceBinder is resoloved in onServiceConnected()
        bindService(new Intent(this, MyService.class),myServiceConnection, Context.BIND_AUTO_CREATE);
        // You will get a null point reference here, if you try to use MyServiceBinder immediately.
        MyServiceBinder.doSomething(); // <-- not yet resolved so Null point reference here
      }
    }
    

    A workaround is call MyServiceBinder.doSomething() in myServiceConnection.onServiceConnected(), or perform MyServiceBinder.doSomething() by some user interaction (e.g. button click), as the lag after you call bindService() and before system get a reference of myServiceBinder is quite soon. as long as you are not using it immediately, you should be just fine.

    Check out this SO question CommonsWare's answer for more details.

提交回复
热议问题