应用程序销毁后,Google api客户端断开连接

时间:2016-04-27 13:02:19

标签: android geolocation google-api-client android-fusedlocation

在我的项目中,我使用谷歌api客户端创建了获取位置的后台服务。

我的问题是当应用程序被销毁,服务正在运行但谷歌api客户端自动断开连接并且无法获得lat-lang。我不想失去联系。

这是我的服务类代码

public class LocationService extends Service  implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    Location mLastLocation;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    String lat, lon;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {


        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        if (mGoogleApiClient == null) {
            buildGoogleApiClient();
        }else{
            mGoogleApiClient.connect();
        }

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        mLocationRequest.setInterval(100); // Update location every second



        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);


        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            lat = String.valueOf(mLastLocation.getLatitude());
            lon = String.valueOf(mLastLocation.getLongitude());

        }
        updateUI();
    }

    @Override
    public void onConnectionSuspended(int i) {
           mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        lat = String.valueOf(location.getLatitude());
        lon = String.valueOf(location.getLongitude());
        updateUI();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        buildGoogleApiClient();
    }
    synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();


    }



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

    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        //setUpLocationClientIfNeeded();
        if(!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting())
        {
            mGoogleApiClient.connect();
        }

        return START_STICKY;

    }
    void updateUI() {
        Log.d("LatLongGPS", lat + "==========" + lon);
        Toast.makeText(getApplicationContext(), "Service"+lat + "==========" + lon, Toast.LENGTH_LONG).show();
    }
}

0 个答案:

没有答案
相关问题