0

我正在尝试在我的 android 应用程序上获取 GPS 坐标。

Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
LocationManager locationManager =
        (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

Intent i = new Intent(context, IntentListener.class);
i.setAction(Actions.ACTION_UPDATE_LOCATION);
PendingIntent pi = PendingIntent.getBroadcast(
        context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
String provider = locationManager.getBestProvider(criteria, true);
if (provider == null) return;
locationManager.requestLocationUpdates(provider, 90 * 1000, 30, pi);

这是接收代码。

Intent service = new Intent(context, WorkerService.class);
service.setAction(Actions.ACTION_UPDATE_LOCATION);
Location location = (Location) intent.getExtras().get(
        LocationManager.KEY_LOCATION_CHANGED);

if (location == null) { // <-- Always true
    return;
}

service.putExtra("lat", location.getLatitude());
service.putExtra("lon", location.getLongitude());
context.startService(service);

如您所见,我无法通过调用 intent.getExtras()... 等获取 Location 实例。返回值始终为 null。我正在使用 geo fix 经度纬度在运行 android 4.1.2 和 telnet 客户端的模拟器上进行测试。有谁知道出了什么问题?谢谢。

PS Manifest 包含所有必需的权限,并且在模拟器中启用了 GPS。

PPS 此应用程序是一个企业应用程序,作为服务运行,没有 UI,应该收集 GPS 坐标。

4

7 回答 7

5

您随便提到您正在模拟器上进行测试。模拟器本身不接收模拟位置;您必须通过 DDMS 接口专门发送它们。

此外,由于模拟器中的错误,传入位置的时间偏移设置为午夜,因此您的位置条件可能与它不匹配。

我强烈建议您使用物理设备进行测试,以确认问题仍然存在。

于 2013-11-13T19:27:46.187 回答
2

使用我的代码获取位置,因为它正在工作。我从这段代码中得到了越来越多的时间,甚至得到了准确的电话号码的地址。

在 AndroidGPSActivity.java 中,在 btnShowLocation 侦听器方法中,我成功获得了纬度和经度。之后你可以做任何你想做的事。

之前打开你的 gps 和 wifi,因为我猜在 API 11 之后你不能以编程方式打开 GPS(不确定 API 级别):-

首先在你的 android manifest 文件中添加所有这些权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

AndroidGPSTrackingActivity.java*

package com.example.gpstracking;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class AndroidGPSTrackingActivity extends Activity {

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;
    ToggleButton gpstoggle,wifitoggle,datatoggle;
    static WifiManager wifiManager;
    LocationManager lm;
    WebView web;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        gpstoggle = (ToggleButton) findViewById(R.id.gps);
        wifitoggle = (ToggleButton) findViewById(R.id.wifi);

        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 

        lm = (LocationManager) getSystemService(LOCATION_SERVICE);

        //gps toggle
        gpstoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    final Intent poke = new Intent();
                    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3")); 
                    getApplicationContext().sendBroadcast(poke);
                }
                else{
                    final Intent poke = new Intent();
                    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3")); 
                    getApplicationContext().sendBroadcast(poke);
                }
            }
        });
        //wifi toggle
        wifitoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    wifiManager.setWifiEnabled(true);
                }
                else{
                    wifiManager.setWifiEnabled(false);
                }
            }
        });

        //data toggle
        datatoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    ConnectivityManager dataManager;
                    dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                    Method dataMtd = null;

                    try {
                        dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
                        dataMtd.setAccessible(true);
                        dataMtd.invoke(dataManager, true);

                    } catch (NoSuchMethodException e1) {
                        e1.printStackTrace();
                    }
                    catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }  
                    catch (SecurityException e) {
                        e.printStackTrace();
                    } 

                }
                else{
                    ConnectivityManager dataManager;
                    dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                    Method dataMtd = null;

                    try {
                        dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
                        dataMtd.setAccessible(false);
                        dataMtd.invoke(dataManager, false);


                    } catch (NoSuchMethodException e1) {
                        e1.printStackTrace();
                    }
                    catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }  
                    catch (SecurityException e) {
                        e.printStackTrace();
                    } 

                }
            }
        });

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {        
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
                    List<Address> addresses = null;
                    try {
                        addresses = gcd.getFromLocation(latitude, longitude, 1);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(!(addresses == null)){
                        if (!addresses.isEmpty() ){
                            System.out.println(addresses.get(0).getLocality());

                            Address address = addresses.get(0);

                            String addressText = String.format("%s, %s, %s, %s, %s, %s",
                                    address.getAddressLine(0),
                                    address.getAddressLine(1),
                                    address.getAddressLine(2),
                                    address.getAddressLine(3),
                                    address.getPhone(),
                                    address.getPremises());

                            System.out.println(addressText);

                            // \n is for new line
                            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                        }else{
                            // can't get location
                            // GPS or Network is not enabled
                            // Ask user to enable GPS/network in settings
                            gps.showSettingsAlert();
                        }
                    }else{
                        // can't get location
                        // GPS or Network is not enabled
                        // Ask user to enable GPS/network in settings
                        gps.showSettingsAlert();
                    }

                }

            }
        });
    }

}

GPSTracker.java

package com.example.gpstracking;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            boolean wifiEnabled = AndroidGPSTrackingActivity.wifiManager.isWifiEnabled();

            ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

            this.canGetLocation = true;

            // if DATA Enabled get lat/long using WIFI Services
            if (activeNetwork.isConnected()) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                }
            }
            // if WIFI Enabled get lat/long using WIFI Services
            if (wifiEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);

                    }
                }
            }
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

主要的.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/btnShowLocation" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Location"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <ToggleButton
        android:id="@+id/gps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnShowLocation"
        android:layout_alignRight="@+id/btnShowLocation"
        android:layout_marginBottom="49dp"
        android:layout_marginRight="72dp"
        android:text="GPS"
         />

    <ToggleButton
        android:id="@+id/wifi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/gps"
        android:layout_alignBottom="@+id/gps"
        android:layout_alignLeft="@+id/btnShowLocation"
        android:layout_marginLeft="79dp"
        android:text="WIFI" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/gps"
        android:layout_alignLeft="@+id/btnShowLocation"
        android:text="GPS"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_marginLeft="61dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="WIFI"
        android:textSize="15sp" />

</RelativeLayout>

AndroidManifest.xml

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

<uses-sdk android:minSdkVersion="8" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".AndroidGPSTrackingActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

</manifest>
于 2013-11-17T11:50:03.780 回答
1

使用新的 Location API

您必须将 Google Play 服务包含到您的项目中。在 onCreate 中添加:

mIntentService = new Intent(this,LocationService.class);
mPendingIntent = PendingIntent.getService(this, 1, mIntentService, 0);

int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if(resp == ConnectionResult.SUCCESS){
        locationclient = new LocationClient(this,this,this);
        locationclient.connect();
    }

你必须重写这些方法:

@Override
protected void onDestroy() {
    super.onDestroy();
    if(locationclient!=null)
        locationclient.disconnect();
}

@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "onConnected");
    //to get last location
    Location loc =locationclient.getLastLocation();

    //to get updates via service
    locationrequest = LocationRequest.create();
    locationrequest.setInterval(100);
    locationclient.requestLocationUpdates(locationrequest, mPendingIntent);
}

@Override
public void onDisconnected() {
    Log.i(TAG, "onDisconnected");
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    Log.i(TAG, "onConnectionFailed");
}

@Override
public void onLocationChanged(Location location) {
    if(location!=null){
        Log.i(TAG, "Location Request :" + location.getLatitude() + "," + location.getLongitude());
    }

}

这是我为每个新位置创建通知的服务,您可以删除它并在那里更新位置。

public class LocationService extends IntentService {

private String TAG = this.getClass().getSimpleName();
public LocationService() {
    super("Fused Location");
}

public LocationService(String name) {
    super("Fused Location");
}

@Override
protected void onHandleIntent(Intent intent) {

        Location location = intent.getParcelableExtra(LocationClient.KEY_LOCATION_CHANGED);
        if(location !=null){
            Log.i(TAG, "onHandleIntent " + location.getLatitude() + "," + location.getLongitude());
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
            Builder noti = new NotificationCompat.Builder(this);
            noti.setContentTitle("Fused Location");
            noti.setContentText(location.getLatitude() + "," + location.getLongitude());
            noti.setSmallIcon(R.drawable.ic_launcher);

            notificationManager.notify(1234, noti.build());

        }

}

}

于 2013-11-12T13:04:02.077 回答
0

按照教程在 Android 应用中获取位置

于 2013-11-08T11:55:07.700 回答
0

您应该通过实施来获取您的位置LocationListener

@Override
public void onLocationChanged(Location loc) {
}
于 2013-11-08T11:56:52.623 回答
0

看看这个实现,效果很好,我已经在几个设备上测试过它。

package ro.gebs.captoom.activities;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bugsense.trace.BugSenseHandler;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import ro.gebs.captoom.R;
import ro.gebs.captoom.database.ReceiptDataSource;
import ro.gebs.captoom.utils.Constants;
import ro.gebs.captoom.utils.Utils;

public class LocationActivity extends FragmentActivity {

    private GoogleMap map;
    private long rec_id;
    private String address;
    private Marker selectedLoc;
    private boolean isSessionClosed;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        BugSenseHandler.initAndStartSession(this, Constants.BugSenseKEY);
        setContentView(R.layout.preview_location);
        RelativeLayout cancel_btn = (RelativeLayout) findViewById(R.id.cancel_btn);
        LinearLayout save_location_btn = (LinearLayout) findViewById(R.id.delete_btn);

        save_location_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (address != null) {
                    ReceiptDataSource r = new ReceiptDataSource();
                    r.updateReceiptLocation(rec_id, address);
                    Intent returnIntent = new Intent(getBaseContext(), EditReceiptActivity.class);
                    returnIntent.putExtra("result", address);
                    setResult(RESULT_OK, returnIntent);
                    finish();
                } else {
                    Utils.showToast(getApplicationContext(), getString(R.string.c_unknownLocation), Toast.LENGTH_SHORT);
                }
            }
        });

        cancel_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        if (map == null) {

            map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

            if (isGoogleMapsInstalled()) {
                if (map != null) {
                    retrieveLocation();
                }
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Install Google Maps");
                builder.setCancelable(false);
                builder.setPositiveButton("Install", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.apps.maps"));
                        startActivity(intent);
                        finish();
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isSessionClosed) {
            BugSenseHandler.startSession(this);
            isSessionClosed = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        BugSenseHandler.closeSession(this);
        isSessionClosed = true;
    }

    @Override
    public void onBackPressed() {
        map.clear();
        super.onBackPressed();
    }

    private void retrieveLocation() {
        Intent intent = getIntent();
        address = intent.getStringExtra("location");
        assert address != null;
        if (address.equalsIgnoreCase("")) {
            address = Utils.getCurrentLocation(LocationActivity.this);
        }
        rec_id = intent.getLongExtra("receipt_to_update_location", 0);
        final Geocoder geocoder = new Geocoder(this, Locale.US);
        double latitude = 0, longitude = 0;
        try {
            List<Address> loc = geocoder.getFromLocationName(address, 5);
            if (loc.size() > 0) {
                latitude = loc.get(0).getLatitude();
                longitude = loc.get(0).getLongitude();
            } else {
                Utils.showToast(LocationActivity.this, getString(R.string.UnableToFindLocation), Toast.LENGTH_SHORT);
            }


            selectedLoc = map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(address).draggable(true));
            map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
                @Override
                public void onMarkerDragStart(Marker marker) {

                }

                @Override
                public void onMarkerDrag(Marker marker) {

                }

                @Override
                public void onMarkerDragEnd(Marker marker) {
                    try {
                        List<Address> addresses = geocoder.getFromLocation(selectedLoc.getPosition().latitude, selectedLoc.getPosition().longitude, 1);
                        StringBuilder sb = new StringBuilder();
                        if (addresses.size() > 0) {
                            Address address = addresses.get(0);

                            if (address.getAddressLine(0) != null)
                                sb.append(address.getAddressLine(0)).append(", ");
                            if (address.getLocality() != null)
                                sb.append(address.getLocality()).append(", ");
                            if (address.getCountryName() != null)
                                sb.append(address.getCountryName());
                        }

                        address = sb.toString();
                    } catch (IOException e) {
                    }

                }
            });

            map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12));

            // Zoom in, animating the camera.
            map.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);

        } catch (IOException e) {
            Log.e("IOException", e.getMessage());
            Utils.showToast(LocationActivity.this, getString(R.string.c_unknownLocation), Toast.LENGTH_LONG);
        }

    }

    public boolean isGoogleMapsInstalled() {
        try {
            getPackageManager().getApplicationInfo("com.google.android.apps.maps", 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }


}
于 2013-11-08T12:08:40.003 回答
0

我看到你在得到额外的东西后实现了 intent.putExtra !您应该在接收位置数据的活动中执行 put,当您想从 intent.extra 接收数据时,您应该这样做:

Bundle extras = getIntent().getExtras();
    if (extras != null) {
        latitude= (double)extras.getDouble("lat");
        longitude=(double)extras.getDouble("lon");
    }
于 2013-11-12T10:07:53.637 回答