2

我正在尝试获取我的 android 手机的当前位置并在吐司中显示经度和纬度。这是我写的一个函数。在调试代码时,我看到控件永远不会进入 onLocationChanged 函数。

从下面的android文档看起来,当我调用“locationMgr.requestLocationUpdates”时,它应该调用回调函数onLocationChanged。但这似乎并没有在我的代码中发生。 http://developer.android.com/training/basics/location/currentlocation.html

我检查了我的手机是否打开了 GPS。我无法弄清楚以下代码中有什么问题。请帮忙。

  public void getCurrentLocation(){
            LocationManager locationMgr;
    locationMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    LocationListener listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
           // A new location update is received.  Do something useful with it  

                    String latitude = "latitude: " + location.getLatitude();
                    String longitude = "longitude: " + location.getLongitude();
                    String toastString = "location is" + latitude + "," +longitude;
                    Toast.makeText( getApplicationContext(),toastString,Toast.LENGTH_SHORT).show();

            }
        @Override  
          public void onProviderDisabled(String provider) {  
           // No code here  
          }  

          @Override  
          public void onProviderEnabled(String provider) {  
           // No code here  
          }  

          @Override  
          public void onStatusChanged(String provider, int status,Bundle extras)   
          {  
           // No code here  
          }  
    };

    locationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, listener);
}

我的清单文件中也有以下两行。

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

谢谢您的帮助。

我正在使用 Eclipse,而我的手机(操作系统:Thunderbolt)的 API 级别为 15,目标为 4.0.4。

4

4 回答 4

1

问题是 google-play-services 库。我必须下载库代码并在 Eclipse 中编译它。然后我在我的项目中添加了库的路径。这解决了问题。早些时候,我在我的项目中包含了 google-play-services .jar 文件,但它不起作用。不知道为什么。

于 2013-05-23T18:56:56.963 回答
1

您没有获得位置的原因有很多。

1.)如果您试图在模拟器上获取位置。然后您必须使用 DDMS 手动推送坐标。

2.) 如果您在设备上检查它,但仍然没有获得位置。然后正如你所说,你期待它来自 GPS。那么你应该有晴朗的天空视图来获得它。由于 GPS 接收器不能在屋顶或某些障碍物下工作。他们必须有天空视野。

3.) 您可以使用 wi-fi 或 cell-Tower 获取位置。如果位置准确性不那么重要,您也可以选择最后一个已知位置。

我认为第二点可能会解决您的问题。

于 2013-05-01T05:37:17.377 回答
1

试试Android GPS,位置管理器教程代码。本教程也解决了我的位置跟踪问题。

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.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = 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
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    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 (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // 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) {
          latitude = location.getLatitude();
          longitude = location.getLongitude();
    }

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

}

每当您需要更新位置时,只需致电

gpsTracker.getLocation();
于 2013-05-01T05:43:29.753 回答
0

这是我编写的示例,它使用 LocationManager 每两分钟获取一次位置数据。它并不完美,但应该足以解决您的问题:可以在此处找到 关注:

@Override
public void onLocationChanged(final Location location) {
    this.location=location;
    final Handler handler = new Handler();
    Timer ourtimer = new Timer();
    TimerTask timerTask = new TimerTask() {
        int cnt=1;
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    Double latitude = location.getLatitude();
                    Double longitude = location.getLongitude();
                    Double altitude = location.getAltitude();
                    Float accuracy = location.getAccuracy();
                    textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt);
                    try {
                        jsonData = new JSONObject();
                        jsonData.put("Latitude", latitude);
                        jsonData.put("Longitude", longitude);
                        jsonData.put("Altitude", altitude);
                        jsonData.put("Accuracy", accuracy);

                        System.out.println(jsonData.toString()); //not required, for testing only   
                        if(url!=null) {
                            new HttpPostHandler().execute();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    cnt++;
                }
            });
        }};
    ourtimer.schedule(timerTask, 0, 120000);
于 2013-05-01T02:26:46.573 回答