【问题标题】:How to create a IntentService to check if GoogleApiClient is not null android如何创建一个 IntentService 来检查 GoogleApiClient 是否为空 android
【发布时间】:2017-07-04 07:27:48
【问题描述】:

在我的项目中,我使用“GoogleApiClient”每 5 秒发出一次位置请求,问题是,如果我关闭 GPS 然后重新打开应用程序,它会崩溃,因为 mGoogleApiClient 对象当前为空!我只是在onRestart做一个简单的检查

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

我想要的是创建一个我可以在每次对象mGoogleApiClient 为空时调用的东西,这样它就可以在后台尝试直到可以继续! startLocationUpdate(); 内部我正在使用这个:

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();
    }

可能是这样的:

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

我已经使用IntentServiceGeocoder 来获取地址!

【问题讨论】:

  • 你可以试试 Android Service 和 Timer with in service

标签: java android google-api-client intentservice android-intentservice


【解决方案1】:

在此条件下检查是否启用 GPS 的 onRestart

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

【讨论】:

  • 我已经做到了,我想要的是继续尝试直到连接恢复!
  • 使用 Handler 然后它会在给定时间后继续检查 GPS 是否可用
【解决方案2】:

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

【讨论】:

  • 手动不行!!它必须是某种计时器,所以每 5 秒重试一次!
  • 你可以使用处理程序类方法 scheduleatFixedRate 设置它,您必须指定该任务应该执行的时间间隔
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2013-01-05
相关资源
最近更新 更多