简体   繁体   English

Android定位应用崩溃

[英]Android location app crash

I'm new to android developing, and i'm tring to create an app which gets your coordinates like this tutorial http://developer.android.com/training/location/receive-location-updates.html but my app crashes. 我是android开发的新手,我正试图创建一个应用程序,它可以像本教程http://developer.android.com/training/location/receive-location-updates.html这样获取您的坐标,但是我的应用程序崩溃了。 I didn't to the last part "Save the State of the Activity" because i dont know what my LOCATION_KEY or REQUESTING_LOCATION_UPDATES_KEY is. 我没有最后一部分“保存活动状态”,因为我不知道我的LOCATION_KEY或REQUESTING_LOCATION_UPDATES_KEY是什么。

my code: 我的代码:

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

}

And this is my manifest: 这是我的清单:

<?xml version="1.0" encoding="utf-8"?>

<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>

When i run my app with the emulator (which doesn't have google services) and i click the update google services i get this error (i don't think this is the problem because i have google services on my phone) : 当我使用模拟器运行我的应用程序(不具有google服务)并且单击更新google服务时,出现此错误(我不认为这是问题所在,因为我的手机上装有google服务):

   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)

I tried to delete the startLocationUpdates part and it doesn't crash anymore... but also it doesn't update location... 我试图删除startLocationUpdates部分,它不再崩溃了……但是它也没有更新位置……

SOLVED IT 解决了它

so the problem was that i declared mLocationRequest twice at the start of the project: 所以问题是我在项目开始时两次声明了mLocationRequest:

LocationRequest mLocationRequest; LocationRequest mLocationRequest;

and in 和在

createLocationRequest() createLocationRequest()

LocationRequest mLocationRequest = new LocationRequest(); LocationRequest mLocationRequest = new LocationRequest();

i changed in crateLocationRequest LocationRequest mLocationRequest = new LocationRequest(); 我在crateLocationRequest中更改了LocationRequest mLocationRequest = new LocationRequest(); to mLocationRequest = new LocationRequest(); 到mLocationRequest = new LocationRequest(); and now it doesn't crash. 现在不会崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM