打开/关闭GPS后,GoogleApiClient将停止正常工作

时间:2017-02-20 14:34:40

标签: android gps google-api-client android-location android-googleapiclient

我正在尝试实现抽象Activity,其继承者可以获取Location数据。我严格遵循 this guide ,这看起来非常简单。

但毕竟我有一些问题。即使GPS已关闭,Google API也应传递位置数据,从网络数据甚至是其他应用的被动数据中获取此信息。但就我而言,它仅适用于启用GPS。

另一个问题是当我关闭/打开GPS时会发生什么。在我的情况下,我根本无法获得任何数据。

这是让一切都完成的课程。

public abstract class LocationProviderActivity extends BaseDrawerActivity
        implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {


    private final String TAG = "LOCATION";
    GoogleApiClient client;
    protected Location location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (client == null) {
            client = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
    }

    @Override
    protected void onStart() {
        client.connect();
        Log.i(TAG, "Connected");
        super.onStart();
    }

    @Override
    protected void onStop() {
        client.disconnect();
        Log.i(TAG, "Disconnected");
        super.onStop();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //TODO
            return;
        }
        location = LocationServices.FusedLocationApi.getLastLocation(client);
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Location services connected.");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i(TAG, "Location services suspended. Please reconnect.");
    }

    @Override
    public void onLocationChanged(Location location) {

    }
}

0 个答案:

没有答案