[英]Android LocationClient not connecting
My code without 我的代码没有
mCurrentLocation = mLocationClient.getLastLocation();
works just fine, but when I add it the app doesnt start. 工作正常,但是当我添加它时,该应用程序无法启动。
package com.example;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 0;
private GoogleMap googleMap;
private LocationClient mLocationClient;
private Location mCurrentLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
// googleMap = ((MapFragment) getFragmentManager().findFragmentById(
// R.id.map)).getMap();
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
// latitude and longitude
double latitude = 97;
double longitude = 122;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps ");
marker.icon(null);
// adding marker
googleMap.addMarker(marker);
googleMap.setMyLocationEnabled(true);
TextView text = (TextView) findViewById(R.id.textview);
if(servicesConnected()){
text.setText("Google Play services is available.");
}else{
text.setText("Google Play services is UNAVAILABLE.");
}
mLocationClient = new LocationClient(this, this, this);
mCurrentLocation = mLocationClient.getLastLocation(); //***********************
}
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode =
GooglePlayServicesUtil.
isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates",
"Google Play services is available.");
// Continue
return true;
// Google Play services was not available for some reason
} else {
Log.d("Location Updates",
"Google Play services is UNAVAILABLE.");
return false;
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
@Override
protected void onResume() {
super.onResume();
initilizeMap();
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
@Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
}
}
/*
* Called when the Activity becomes visible.
*/
@Override
protected void onStart() {
super.onStart();
// Connect the client.
mLocationClient.connect();
}
/*
* Called when the Activity is no longer visible.
*/
@Override
protected void onStop() {
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
super.onStop();
}
}
right now I am not usin the value that im getting from that Location and Eclipse gives me a warning because of that but I dont think that should crash the app. 现在,我还没有从该位置和Eclipse中获得的价值给我一个警告,因此,我不认为这应该会使应用程序崩溃。 even if I gave use to that value it still crashes.
即使我习惯了该值,它仍然崩溃。
XML XML格式
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.reachmenow.MainActivity" >
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_weight="9"
android:layout_height="0dp" />
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp" >
</TextView>
</LinearLayout>
Manifest 表现
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.reachmenow"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- The following two permissions are not required to use Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAZQpyuuupl4aRHAzfxkaV4jlAmM9nRwxA" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
</manifest>
LogCat Exceptions LogCat异常
08-21 12:07:53.071: W/nalizableReferenceQueue(31511): java.io.FileNotFoundException: com/google/inject/internal/util/$Finalizer.class
08-21 12:50:57.135: W/dalvikvm(32361): threadid=1: thread exiting with uncaught exception (group=0x414ea2a0)
08-21 12:50:57.165: E/AndroidRuntime(32361): FATAL EXCEPTION: main
08-21 12:50:57.165: E/AndroidRuntime(32361): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.reachmenow/com.reachmenow.MainActivity}: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
08-21 12:50:57.165: E/AndroidRuntime(32361): Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
I believe I found the problem, but still don't know how to solve it. 我相信我找到了问题,但仍然不知道如何解决。 I am calling
我在打电话
....
mLocationClient = new LocationClient(this, this, this);
mCurrentLocation = mLocationClient.getLastLocation();
....
on the onCreate()
method but LocationClient
is connected on the onStart()
method that is called after onCreate()
, therefore when I call it, a connection to the client has not been made yet. 在
onCreate()
方法上,但是LocationClient
连接在onCreate()
之后调用的onStart()
方法上,因此,当我调用它时,尚未建立到客户端的连接。
Is this really the issue? 这真的是问题吗? What is the correct procedure here?
这里正确的程序是什么? where should I call
我应该在哪里打电话
mLocationClient = new LocationClient(this, this, this);
mCurrentLocation = mLocationClient.getLastLocation();
in order to get access to that location. 为了访问该位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.