Android 已连接到服务,但在I';我想用它

Android 已连接到服务,但在I';我想用它,android,binding,service,gps,nullpointerexception,Android,Binding,Service,Gps,Nullpointerexception,我有一个问题,当我试图使用我的服务时,程序失败了。它从第一个活动开始: startService(new Intent(this, GPSService.class)); 然后在另一个活动(称为Main)中,我有: protected GPSService gService; protected boolean mIsBound = false; protected ServiceConnection mConnection = new ServiceConnection() {

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

startService(new Intent(this, GPSService.class));
然后在另一个活动(称为Main)中,我有:

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);
    }
}
公共类GPSService扩展服务{
专用静态最终字符串TAG=“GPS\U服务”;
私有位置管理器mLocationManager=null;
专用静态最终int位置_间隔=1000;
专用静态最终浮动位置_距离=10f;
位置当前位置;
私有类LocationListener实现android.location.LocationListener{
位置mLastLocation;
公共位置侦听器(字符串提供程序)
{
Log.e(标记“LocationListener”+提供者);
mLastLocation=新位置(提供商);
}
@凌驾
已更改位置上的公共无效(位置)
{
Log.e(标签“onLocationChanged:+位置);
如果(位置!=null){
mLastLocation.set(位置);
currentLocation=mLastLocation;
}
}
@凌驾
公共无效onProviderDisabled(字符串提供程序)
{
Log.e(标记“onProviderDisabled:+提供程序”);
}
@凌驾
公共无效onProviderEnabled(字符串提供程序)
{
Log.e(标记“onProviderEnabled:+提供程序”);
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra)
{
Log.e(标记“onStatusChanged:+提供者”);
}
} 
LocationListener[]mlLocationListeners=新LocationListener[]{
新LocationListener(LocationManager.GPS_提供程序),
新LocationListener(LocationManager.NETWORK\u提供程序)
};
private IBinder mBinder=新的GPSServiceBinder();
公共类GPSServiceBinder扩展了Binder{
公共GPSService getServerInstance(){
返回GPSService.this;
}
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId)
{
Log.e(标记“onStartCommand”);
super.onStartCommand(intent、flags、startId);
返回开始时间;
}
@凌驾
公共IBinder onBind(意向){
返回mBinder;
}
int minTime=60000;
浮心距离=15;
@凌驾
public void onCreate()
{
super.onCreate();
Log.e(标记为“onCreate”);
初始化ElocationManager();
试一试{
mLocationManager.RequestLocationUpdate(
LocationManager.NETWORK_提供程序、位置间隔、位置距离、,
mLocationListeners[1]);
}catch(java.lang.SecurityException ex){
Log.i(标记“无法请求位置更新,忽略”,例如);
}捕获(IllegalArgumentException ex){
Log.d(标记“网络提供商不存在”+ex.getMessage());
}
试一试{
mLocationManager.RequestLocationUpdate(
LocationManager.GPS\u提供程序、位置\u间隔、位置\u距离、,
mLocationListeners[0]);
}catch(java.lang.SecurityException ex){
Log.i(标记“无法请求位置更新,忽略”,例如);
}捕获(IllegalArgumentException ex){
Log.d(标记“gps提供程序不存在”+ex.getMessage());
}
}
公共位置getLocation()
{   
返回当前位置;
}
公共布尔getGPSstatus()
{
if(mLocationManager.isProviderEnabled(LocationManager.GPS_提供程序)){
返回true;
}否则{
返回false;
}
}
@凌驾
公共空间
{
Log.e(标签“onDestroy”);
super.ondestory();
if(mLocationManager!=null){
for(int i=0;i
}

这不起作用:

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


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

我已创建了一个方法,并在“我的活动”中单击按钮时被调用。但是当我尝试使用gService时,我的应用程序仍在使用nullPointer崩溃。在调用
onServiceConnected()
之前,你不能使用
gService
。否则,
gService
仍为空。使用调试器逐步完成它。在serviceconnected()上的
设置断点。确保有人打电话给它。然后在尝试使用它的位置设置断点。如果你仍然有问题,那么就把代码发出去。谢谢你,大卫。我发现了错误-这不是ServiceConnected上的问题,问题是服务返回了null而不是默认位置(0.0,0.0)。