2010-05-15 33 views
6

當我嘗試綁定到已啓動的服務時,在mService.start()行得到空指針異常。我從不同的活動(服​​務開始的地方)做同樣的事情,每一步都是正確的。所有這些活動都是一個應用的一部分。android bindservice

你覺得我做錯了什麼?

public class RouteOnMap extends MapActivity{ 
    private static final int NEW_LOCATION = 1; 
    private static final int GPS_OFF = 2; 

    private MapView mMapView; 
    private ILocService mService; 
    private boolean mServiceStarted; 
    private boolean mBound; 
    private Intent mServiceIntent; 
    private double mLatitude, mLongitude; 

    private ServiceConnection connection = new ServiceConnection() { 
     public void onServiceConnected(ComponentName className, IBinder iservice) { 
      mService = ILocService.Stub.asInterface(iservice); 
      mBound = true; 
     } 

     public void onServiceDisconnected(ComponentName className) { 
      mService = null; 
      mBound = false; 
     } 

    }; 

    public void onCreate(Bundle savedInstanceState){ 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.mapview); 

     mMapView = (MapView) findViewById(R.id.mapview); 
     mMapView.setBuiltInZoomControls(true);  
     mServiceIntent = new Intent(); 
     mLatitude = 0.0; 
     mLongitude = 0.0; 
     mBound = false; 
    } 

    @Override 
    public void onStart(){ 
     super.onStart(); 

     mServiceIntent.setClass(this, LocationService.class); 
     //startService(mServiceIntent); 
     if(!mBound){ 
      mBound = true; 
      this.bindService(mServiceIntent, connection, Context.BIND_AUTO_CREATE); 
     } 
    } 

    @Override 
    public void onResume(){ 
     super.onResume(); 


     try { 
      mService.start(); 
     } catch (RemoteException e) { 
      e.printStackTrace(); 
     } 

    } 

    @Override 
    public void onPause(){ 
     super.onPause(); 

     if(mBound){ 
      this.unbindService(connection); 
     } 
    } 

    @Override 
    protected boolean isRouteDisplayed() { 
     // TODO Auto-generated method stub 
     return false; 
    } 

} 

回答

8

您無法知道服務是否受到onResume()的約束。 bindService()不是阻止呼叫。請撥打onServiceConnected()方法撥打mService.start()

+0

謝謝。從onServiceConnected調用mService.start()工作。你建議從onServiceConnected()總是調用mService方法嗎? – mnish 2010-05-16 11:25:49

+3

直到調用'onServiceConnected()','mService'爲'null'。因此,在你確定'onServiceConnected()'已被調用之前,你不想在'mService'上調用方法。所以,例如,當用戶點擊某個東西時,「mService」可能已經準備就緒。然而,'onResume()'太快了 - 你的'bindService()'請求可能還沒有被處理。 – CommonsWare 2010-05-16 12:05:13

+0

非常感謝您的幫助 – mnish 2010-05-16 17:49:39