简体   繁体   English

如何创建一个IntentService来检查GoogleApiClient是否不为null

[英]How to create a IntentService to check if GoogleApiClient is not null android

In my project I'm using the "GoogleApiClient" to make locations requests each 5 seconds, the problem is, if I turn the GPS off and then reopen the App, it crushes because the mGoogleApiClient object is current null! 在我的项目中,我使用“ GoogleApiClient”每5秒发出一次位置请求,问题是,如果我关闭GPS,然后重新打开App,它会崩溃,因为mGoogleApiClient对象当前为null! I'm just doing a simple check on onRestart 我只是在onRestart上做一个简单的检查

protected void onRestart() {
    super.onRestart();
    if(mGoogleApiClient != null && mGoogleApiClient.isConnected()){
        startLocationUpdate();
    }
}

What I want is create something that I could call every time the object mGoogleApiClient is null so it could try in background until be fine to go on! 我想要的是创建一个每次对象mGoogleApiClient为null时都可以调用的东西,这样它就可以在后台尝试,直到可以继续! Inside of startLocationUpdate(); startLocationUpdate();内部startLocationUpdate(); I'm using this : 我正在使用这个:

mlocationRequest = new LocationRequest();
    mlocationRequest.setInterval(5000);
    mlocationRequest.setFastestInterval(2000);
    mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    try{
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mlocationRequest,MainActivity.this);
    }catch (SecurityException ex){
        Toast.makeText(this, ex.toString(), Toast.LENGTH_SHORT).show();
    }

It could be something like : 可能是这样的:

if(mGoogleApiClient != null){
   LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mlocationRequest,MainActivity.this);
  }else {
   callServiceToTryConnection();
}

I already use IntentService with Geocoder to get the address! 我已经将IntentServiceGeocoder一起使用来获取地址!

Check in onRestart that is GPS is enable or not by this condition 在此情况下检查是否启用了GPS的onRestart

if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
   //Here is your condition if GPS is not connected
}

将处理程序置于连接挂起或连接失败的方法中,该方法尝试检查并重新连接(如果不为null)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM