Java Android位置应用程序崩溃

Java Android位置应用程序崩溃,java,android,android-studio,Java,Android,Android Studio,我是android开发新手,我正在尝试创建一个应用程序,它可以像本教程一样获取您的坐标 但我的应用程序崩溃了。我没有提到最后一部分“保存活动状态”,因为我不知道我的位置键或请求位置更新键是什么 我的代码: import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import androi

我是android开发新手,我正在尝试创建一个应用程序,它可以像本教程一样获取您的坐标 但我的应用程序崩溃了。我没有提到最后一部分“保存活动状态”,因为我不知道我的位置键或请求位置更新键是什么

我的代码:

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.SupportErrorDialogFragment;

import java.text.DateFormat;
import java.util.Date;

public class StepCounter extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1001;
// Unique tag for the error dialog fragment
private static final String DIALOG_ERROR = "dialog_error";
// Bool to track whether the app is already resolving an error
private boolean mResolvingError = false;

//keys


protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";



GoogleApiClient mGoogleApiClient;
TextView mLatitudeText;
TextView mLongitudeText;
TextView mcLatitudeText;
TextView mcLongitudeText;
Location mLastLocation;
Location mCurrentLocation;
LocationRequest mLocationRequest;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_step_counter);

    mLatitudeText = (TextView) findViewById(R.id.lat);
    mLongitudeText = (TextView) findViewById(R.id.lon);
    mcLatitudeText = (TextView) findViewById(R.id.llat);
    mcLongitudeText = (TextView) findViewById(R.id.llon);

    mResolvingError = savedInstanceState != null
            && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
    createLocationRequest();
    buildGoogleApiClient();

}

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

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

@Override
protected void onStop() {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(StepCounter.this);
    dialogBuilder.setMessage("onStop");
    dialogBuilder.setPositiveButton("Ok", null);
    dialogBuilder.show();
    mGoogleApiClient.disconnect();
    super.onStop();
}

public void onConnected(Bundle connectionHint) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    mCurrentLocation = mLastLocation;
    if (mLastLocation != null) {
        mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
        mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
    }
    //modified
    startLocationUpdates();
}

//pana aici merge de aici vine partea cu update

protected void startLocationUpdates() {
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}

protected void createLocationRequest() {
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

@Override
public void onLocationChanged(Location location) {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(StepCounter.this);
    dialogBuilder.setMessage("onLocationChanged");
    dialogBuilder.setPositiveButton("Ok", null);
    dialogBuilder.show();
    mLastLocation = mCurrentLocation;
    mCurrentLocation = location;
    updateUI();
}

public void updateUI()
{
    mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
    mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
    mcLatitudeText.setText(String.valueOf(mCurrentLocation.getLatitude()));
    mcLongitudeText.setText(String.valueOf(mCurrentLocation.getLongitude()));
}
@Override
protected void onPause() {
    super.onPause();
    stopLocationUpdates();
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mGoogleApiClient, this);
}

@Override
public void onResume() {
    super.onResume();
    if (mGoogleApiClient.isConnected()) {
        startLocationUpdates();
    }
}








// De aici partea cu rezolvatu problemei


@Override
public void onConnectionSuspended(int i) {
    //todo nust...
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    if (mResolvingError) {
        // Already attempting to resolve an error.
        return;
    } else if (result.hasResolution()) {
        try {
            mResolvingError = true;
            result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
        } catch (IntentSender.SendIntentException e) {
            // There was an error with the resolution intent. Try again.
            mGoogleApiClient.connect();
        }
    } else {
        // Show dialog using GoogleApiAvailability.getErrorDialog()
        showErrorDialog(result.getErrorCode());
        mResolvingError = true;
    }
}

// The rest of this code is all about building the error dialog

/* Creates a dialog for an error message */
private void showErrorDialog(int errorCode) {
    // Create a fragment for the error dialog
    ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
    // Pass the error that should be displayed
    Bundle args = new Bundle();
    args.putInt(DIALOG_ERROR, errorCode);
    dialogFragment.setArguments(args);
    dialogFragment.show(getFragmentManager(), "errordialog");
}

/* Called from ErrorDialogFragment when the dialog is dismissed. */
public void onDialogDismissed() {
    mResolvingError = false;
}


/* A fragment to display an error dialog */
public static class ErrorDialogFragment extends DialogFragment {
    public ErrorDialogFragment() { }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Get the error code and retrieve the appropriate dialog
        int errorCode = this.getArguments().getInt(DIALOG_ERROR);
        return GoogleApiAvailability.getInstance().getErrorDialog(
                this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        ((StepCounter) getActivity()).onDialogDismissed();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_RESOLVE_ERROR) {
        mResolvingError = false;
        if (resultCode == RESULT_OK) {
            // Make sure the app is not already connected or attempting to connect
            if (!mGoogleApiClient.isConnecting() &&
                    !mGoogleApiClient.isConnected()) {
                mGoogleApiClient.connect();
            }
        }
    }
}
private static final String STATE_RESOLVING_ERROR = "resolving_error";

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}

}
这是我的清单:

<?xml version="1.0" encoding="utf-8"?>
我试图删除startLocationUpdates部分,但它不再崩溃。。。但它也不会更新位置…

解决了它

所以问题是,我在项目开始时两次声明了mLocationRequest:

位置请求mLocationRequest

而且

createLocationRequest()

LocationRequest MLLocationRequest=新的LocationRequest()

我在板条箱中更改了LocationRequest LocationRequest MLLocationRequest=新LocationRequest();to mLocationRequest=新位置请求();现在它没有崩溃。

解决了它

所以问题是,我在项目开始时两次声明了mLocationRequest:

位置请求mLocationRequest

而且

createLocationRequest()

LocationRequest MLLocationRequest=新的LocationRequest()


我在板条箱中更改了LocationRequest LocationRequest MLLocationRequest=新LocationRequest();to mLocationRequest=新位置请求();现在它没有崩溃。

至少有人能告诉我什么是位置密钥或请求位置更新密钥吗?我怀疑StartLocationUpdate有问题,因为当我删除它时,它不会崩溃,即使我让它这样做,我也不会从LocationChanged获取警报对话框至少有人能告诉我什么是LOCATION\u KEY或请求什么是LOCATION\u UPDATES\u KEY吗?我怀疑StartLocationUpdate有问题,因为当我删除它时,它不会崩溃,即使我让它存在,我也不会从locationChanged获得alertdialog
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    //android:theme="@android:style/Theme.Holo"
    <activity
        android:name=".LoginScreen"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Register"
        android:label="@string/title_activity_register" >
    </activity>
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
    </activity>
    <activity
        android:name=".StepCounter"
        android:label="@string/title_activity_step_counter" >
    </activity>
</application>
   08-26 09:54:24.640    7191-7191/com.persasrl.paul.quickfit E/SettingsRedirect﹕ Can't redirect to app settings for Google Play services
08-26 09:54:24.653    7191-7191/com.persasrl.paul.quickfit D/AndroidRuntime﹕ Shutting down VM
08-26 09:54:24.654    7191-7191/com.persasrl.paul.quickfit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.persasrl.paul.quickfit, PID: 7191
java.lang.RuntimeException: Unable to pause activity {com.persasrl.paul.quickfit/com.persasrl.paul.quickfit.StepCounter}: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3613)
        at android.app.ActivityThread.access$1300(ActivityThread.java:151)
        at        android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
 Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
        at com.google.android.gms.common.api.zzf.zzb(Unknown Source)
        at com.google.android.gms.common.api.zzg.zzb(Unknown Source)
        at com.google.android.gms.location.internal.zzd.removeLocationUpdates(Unknown Source)
        at com.persasrl.paul.quickfit.StepCounter.stopLocationUpdates(StepCounter.java:148)
        at com.persasrl.paul.quickfit.StepCounter.onPause(StepCounter.java:144)
        at android.app.Activity.performPause(Activity.java:6101)
        at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1310)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3603)