2015-08-26 122 views
1

我新的Android开发方面,我特林创建一个应用程序,它得到您的坐标,这样的教程http://developer.android.com/training/location/receive-location-updates.html 但我的应用程序崩溃。我没有到最后一部分“保存活动的状态”,因为我不知道我的LOCATION_KEY或REQUESTING_LOCATION_UPDATES_KEY是什么。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"?> 

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

当我跑我的模拟器应用程序(它没有按”没有谷歌服务),我点击th e更新谷歌服务,我得到这个错误(我不认为这是问题,因为我的手机上有谷歌服务):

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) 

我试图删除startLocationUpdates的一部分,它不会再崩溃。 ..但也不会更新位置...

+0

能ATLEAST有人告诉我什么LOCATION_KEY或REQUESTING_LOCATION_UPDATES_KEY是谁? –

+0

我怀疑有与startLocationUpdates一个问题,因为当我删除它,它不会崩溃,即使我让TI是我没有得到locationChanged的alertdialog –

回答

0

解决它

所以问题是,我在项目开始申报mLocationRequest两次:

LocationRequest mLocationRequest;

createLocationRequest()

LocationRequest mLocationRequest =新LocationRequest();

i的crateLocationRequest LocationRequest mLocationRequest改变=新LocationRequest(); mLocationRequest = new LocationRequest();现在它不会崩溃。