2013-05-01 207 views
1

我想获取我的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); 
} 

我在Manifest文件中也有以下两行。

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

谢谢你的帮助。

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

+0

有时重新启动设备会有所帮助。只要检查是否有帮助。 – 2013-05-01 02:25:03

+0

感谢您的及时回复。我试过重新启动我的手机。它仍然不起作用。 – user1549994 2013-05-01 03:24:26

回答

1

的问题是谷歌播放服务库。 我不得不下载库代码并在eclipse中进行编译。然后我在项目中添加了图书馆的路径。这解决了这个问题。 早些时候,我在我的项目中包含了google-play-services .jar文件,但它不起作用。不知道为什么。

0

这里是我写的例子,它使用LocationManager获取每两分钟的位置数据。它并不完美,但应该足以解决您的问题:它可以发现here 聚焦:

@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); 
0

还有,你没有得到位置的几个原因。

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

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

3.)您可以使用wi-fi或手机信号塔获取位置信息。如果位置精度不那么重要,你也可以选择最后一个已知位置。

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

+0

我没有使用模拟器。我正在使用我的android手机。我认为接收GPS的手机是因为我可以在手机上打开Goog​​le Map应用程序,并且能够跟踪我的当前位置。所以我得出结论,GPS工作正常。我错了吗? – user1549994 2013-05-01 21:37:20

+0

是的,因为谷歌地图使用缓存和您之前已知的位置,如果他们没有得到您的新位置,这就是您能够看到谷歌地图的唯一原因。 – 2013-05-02 05:01:27

1

尝试Android GPS, Location Manager Tutorial代码。本教程也解决了我的位置跟踪问题。

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