2013-05-01 206 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();