0

我有一个问题,当我尝试使用我的服务时,程序失败了。它从第一个活动开始:

startService(new Intent(this, GPSService.class));

然后在另一个活动(称为主要)中,我有这个:

protected GPSService gService;
protected boolean mIsBound = false;
    protected ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        GPSServiceBinder  binder = (GPSServiceBinder) service;
        gService = binder.getServerInstance();
        mIsBound = true;
        Toast.makeText(ActionBarActivity.this, "Attached to a process",
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        gService = null;
        Toast.makeText(ActionBarActivity.this, "Deattachhed from process",
                Toast.LENGTH_SHORT).show();
    }
};

protected void doBindService(Activity act) {
    getApplication().bindService(new Intent(act, 
            GPSService.class), mConnection, Context.BIND_AUTO_CREATE);

    mIsBound = true;
    if(mIsBound)
        Toast.makeText(ActionBarActivity.this, "connected",
                Toast.LENGTH_SHORT).show();

};

然后我继承Main,调用doBindService()并尝试使用gService,然后它因NullPointer exeption而失败:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    doBindService(OccupationActivity.this);
            gService.getLocation();

但是来自 onServiceConnected() 的 Toast 可以正常工作。

这是我的服务类:

   public class GPSService extends Service {
private static final String TAG = "GPS_SERVICE";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
Location currentLocation;

private class LocationListener implements android.location.LocationListener{

    Location mLastLocation;

    public LocationListener(String provider)
    {
        Log.e(TAG, "LocationListener " + provider);
        mLastLocation = new Location(provider);
    }

    @Override
    public void onLocationChanged(Location location)
    {
        Log.e(TAG, "onLocationChanged: " + location);
        if (location != null){
            mLastLocation.set(location);
            currentLocation = mLastLocation;                
        }

    }

    @Override
    public void onProviderDisabled(String provider)
    {
        Log.e(TAG, "onProviderDisabled: " + provider);            
    }

    @Override
    public void onProviderEnabled(String provider)
    {
        Log.e(TAG, "onProviderEnabled: " + provider);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras)
    {
        Log.e(TAG, "onStatusChanged: " + provider);
    }


} 


LocationListener[] mLocationListeners = new LocationListener[] {
        new LocationListener(LocationManager.GPS_PROVIDER),
        new LocationListener(LocationManager.NETWORK_PROVIDER)
};


private IBinder mBinder = new GPSServiceBinder();

public class GPSServiceBinder extends Binder {
    public GPSService getServerInstance() {
        return GPSService.this;
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Log.e(TAG, "onStartCommand");
    super.onStartCommand(intent, flags, startId);       
    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

int minTime = 60000;
float minDistance = 15;

@Override
public void onCreate()
{
    super.onCreate();
    Log.e(TAG, "onCreate");
    initializeLocationManager();

    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[1]);
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "network provider does not exist, " + ex.getMessage());
    }
    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[0]);
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "gps provider does not exist " + ex.getMessage());
    }
}


public Location getLocation()
{   
    return currentLocation;
}

public boolean getGPSstatus()
{
    if ( mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ){
        return true;       
    }else{
        return false;
    }

}



@Override
public void onDestroy()
{
    Log.e(TAG, "onDestroy");
    super.onDestroy();
    if (mLocationManager != null) {
        for (int i = 0; i < mLocationListeners.length; i++) {
            try {
                mLocationManager.removeUpdates(mLocationListeners[i]);
            } catch (Exception ex) {
                Log.i(TAG, "fail to remove location listners, ignore", ex);
            }
        }
    }
} 


private void initializeLocationManager() {
    Log.e(TAG, "initializeLocationManager");
    if (mLocationManager == null) {
        mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    }
}

}

4

1 回答 1

0

这是行不通的:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    doBindService(OccupationActivity.this);
    gService.getLocation();

因为当您调用doBindService()它时会尝试绑定到服务,但onServiceConnected()完成服务绑定的回调直到稍后才会发生。这个回调是异步的,它在主线程上运行。这意味着当doBindService()返回到您的代码时,onCreate()您会立即使用该变量gService,但该变量尚未设置为任何值,因为调用onServiceConnected()尚未发生。

您需要将您的呼叫gService.getLocation()onCreate()转移到您的活动中的另一个方法,该方法在被调用时被触发onServiceConnected()

于 2012-09-09T20:59:26.257 回答