Android 位置应用程序上的GoogleAppClient尚未连接

Android 位置应用程序上的GoogleAppClient尚未连接,android,service,Android,Service,我试图从一个位置获取城市和国家,但我发现一个例外:GoogleAppClient尚未连接 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weather);` `if (checkPlayServices()) { buildGoogleApiClient();

我试图从一个位置获取城市和国家,但我发现一个例外:GoogleAppClient尚未连接

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_weather);`
`if (checkPlayServices()) {
        buildGoogleApiClient();
        createLocationRequest();
    }

    displayLocation();
    togglePeriodicLocationUpdates();}
private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "This device is not supported.", Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();
            Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
            StringBuilder builder = new StringBuilder();
            try {
                List<Address> address = geoCoder.getFromLocation(latitude, longitude, 1);
                city = address.get(0).getLocality();
                country = address.get(0).getCountryName();


            } catch (IOException e) {
            } catch (NullPointerException e) {
            }


        } else {

            Toast.makeText(this, "erreur", Toast.LENGTH_LONG).show();
        }
    }


    @Override
    public void onConnected(Bundle bundle) {
        displayLocation();
        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }

    }

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

    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        checkPlayServices();
        if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }


    @Override
    public void onLocationChanged(Location location) {
        // Assign the new location
        mLastLocation = location;

        Toast.makeText(getApplicationContext(), "Location changed!",
                Toast.LENGTH_SHORT).show();

        // Displaying the new location on UI
        displayLocation();

    }

    private void togglePeriodicLocationUpdates() {
        if (!mRequestingLocationUpdates) {

            mRequestingLocationUpdates = true;

            // Starting the location updates
            startLocationUpdates();

            Log.d(TAG, "Periodic location updates started!");

        } else {
            // Changing the button text

            mRequestingLocationUpdates = false;

            // Stopping the location updates
            stopLocationUpdates();

            Log.d(TAG, "Periodic location updates stopped!");
        }
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT); // 10 meters
    }

    protected void startLocationUpdates() {

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

    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
    }
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(右布局、活动和天气)`
`如果(checkPlayServices()){
buildGoogleAppClient();
createLocationRequest();
}
显示位置();
切换PeriodicLocationUpdates();}
私有布尔值checkPlayServices(){
int-resultCode=GooglePlayServicesUtil.isgoogleplayservicesavaailable(this);
if(resultCode!=ConnectionResult.SUCCESS){
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){
GooglePlayServicesUtil.getErrorDialog(结果代码,此,播放服务解决方案请求).show();
}否则{
Toast.makeText(getApplicationContext(),
“不支持此设备。”,Toast.LENGTH\u LONG)
.show();
完成();
}
返回false;
}
返回true;
}
受保护的同步无效BuildGoogleAppClient(){
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API).build();
}
私有void displayLocation(){
mLastLocation=LocationServices.FusedLocationApi
.getLastLocation(MGoogleapClient);
如果(mLastLocation!=null){
双纬度=mLastLocation.getLatitude();
double longitude=mLastLocation.getLongitude();
Geocoder Geocoder=新的Geocoder(这个,Locale.getDefault());
StringBuilder=新的StringBuilder();
试一试{
列表地址=geoCoder.getFromLocation(纬度、经度,1);
city=address.get(0.getLocation();
country=address.get(0.getCountryName();
}捕获(IOE异常){
}捕获(NullPointerException e){
}
}否则{
Toast.makeText(这个“erreur”,Toast.LENGTH_LONG).show();
}
}
@凌驾
未连接的公共空间(捆绑包){
显示位置();
如果(mRequestingLocationUpdates){
startLocationUpdates();
}
}
@凌驾
公共空间连接暂停(int i){
mGoogleApiClient.connect();
}
@凌驾
连接失败的公共void(连接结果){
Log.i(标记,“连接失败:ConnectionResult.getErrorCode()=”
+result.getErrorCode());
}
@凌驾
受保护的void onStart(){
super.onStart();
if(mGoogleApiClient!=null){
mGoogleApiClient.connect();
}
}
@凌驾
受保护的void onResume(){
super.onResume();
checkPlayServices();
if(mgoogleapClient.isConnected()&&mRequestingLocationUpdates){
startLocationUpdates();
}
}
@凌驾
受保护的void onStop(){
super.onStop();
if(mgoogleapClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
@凌驾
受保护的void onPause(){
super.onPause();
stopLocationUpdates();
}
@凌驾
已更改位置上的公共无效(位置){
//分配新位置
mLastLocation=位置;
Toast.makeText(getApplicationContext(),“位置已更改!”,
吐司。长度(短)。show();
//在UI上显示新位置
显示位置();
}
private void togglePeriodicLocationUpdates(){
如果(!mrequestingLocationUpdate){
mRequestingLocationUpdates=true;
//启动位置更新
startLocationUpdates();
Log.d(标记“定期位置更新已开始!”);
}否则{
//更改按钮文本
mRequestingLocationUpdates=false;
//停止位置更新
stopLocationUpdates();
Log.d(标记“定期位置更新已停止!”);
}
}
受保护的void createLocationRequest(){
mlLocationRequest=新位置请求();
mLocationRequest.setInterval(更新间隔);
mLocationRequest.SetFastTestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(位置请求.优先级高精度);
mLocationRequest.setSmallestDisplacement(位移);//10米
}
受保护的void startLocationUpdates(){
LocationServices.FusedLocationApi.RequestLocationUpdate(mgoogleapClient、mlLocationRequest、this);
}
受保护的void stopLocationUpdates(){
LocationServices.FusedLocationApi.RemovelocationUpdate(mgoogleapClient,this);
}
有人知道我为什么会遇到这个异常吗?因为我已经在onStart()方法中连接了api

任何答案都会有帮助:在onStart()之前调用D

onCreate(),因此您在连接到Google API之前请求位置

以下是Android开发站点的生命周期图: