0

我的代码没有

mCurrentLocation = mLocationClient.getLastLocation();

工作得很好,但是当我添加它时,应用程序没有启动。

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

现在我没有使用我从该位置获得的值,因此 Eclipse 给了我一个警告,但我认为这不会导致应用程序崩溃。即使我使用了该值,它仍然会崩溃。

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>

显现

<?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 异常

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

1 回答 1

0

我相信我找到了问题,但仍然不知道如何解决。我打电话

....    
mLocationClient = new LocationClient(this, this, this);
mCurrentLocation = mLocationClient.getLastLocation();
....

onCreate()方法上,但在之后调用LocationClient的方法上连接,因此当我调用它时,尚未建立与客户端的连接。onStart()onCreate()

这真的是问题吗?这里的正确程序是什么?我应该在哪里打电话

mLocationClient = new LocationClient(this, this, this);
mCurrentLocation = mLocationClient.getLastLocation();

为了访问该位置。

于 2014-08-21T17:38:26.077 回答