代码之家  ›  专栏  ›  技术社区  ›  Macarse

服务绑定到活动

  •  2
  • Macarse  · 技术社区  · 14 年前

    这是我的代码:

    public class MainActivity extends Activity {
        private ComponentName mService;
        private Servicio serviceBinder;
    
        private ServiceConnection mConnection = new ServiceConnection() {
               public void onServiceConnected(ComponentName className, IBinder service) {
                 serviceBinder = ((Servicio.MyBinder)service).getService();
               }
    
               public void onServiceDisconnected(ComponentName className) {
                 serviceBinder = null;
               }
            };
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            Intent bindIntent = new Intent(this, Servicio.class);
            bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
        }
    
        @Override
        protected void onStart() {
            serviceBinder.somethingThatTakesTooMuch();
            super.onStart();
        }
    
    
    
    public class Servicio extends Service {
        private final IBinder binder = new MyBinder();
    
        @Override
                public IBinder onBind(Intent intent) {
        return binder;
        }
    
        public int somethingThatTakesTooMuch() {
            return 1;
        }
    
        public class MyBinder extends Binder {
              Servicio getService() {
                return Servicio.this;
              }
        }
    

    当我运行它时, 它在此行中获取NullPointerException:

    serviceBinder.somethingThatTakesTooMuch();
    
    1 回复  |  直到 14 年前
        1
  •  5
  •   synic    14 年前

    你的 onStart 在与服务的连接完成之前调用。不是瞬间的。

    您只能保证在调用OnServiceConnected之后连接服务。只有这样,才能对ServiceBinder调用方法。

    尝试呼叫 serviceBinder.somethingThatTakesTooMuch() 在之后的线上 serviceBinder = ((Servicio.MyBinder)service).getService();