2013-08-01 162 views
1

我試圖讓緯度和經度的當前位置。 然而,當我使用下面的代碼,位置監聽器根本沒有被觸發。 我已經在清單文件中添加了LOCATION權限。無法獲得緯度和經度

任何人都可以幫忙嗎?

下面是Java代碼:

package com.example.setlocaction; 


import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.app.Activity; 
import android.content.Context; 
import android.util.Log; 
import android.widget.Toast; 

public class MainActivity extends Activity{ 
double latitude, longitude, radius; 
LocationManager mlocManager; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    // Acquire a reference to the system Location Manager 
    mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
    // Define a listener that responds to location updates 
    LocationListener locationListener = new LocationListener() 
    {  
     public void onLocationChanged(Location loc) 
     {  
      // Called when a new location is found by the network location provider.  
      Log.i("loc","location changed"); 
      if (loc!=null) 
      { 
       loc.getLatitude(); 
       loc.getLongitude(); 
       String Text = "My current location is: " + 
       "Latitud =" + loc.getLatitude() + 
       "Longitud = " + loc.getLongitude(); 
       Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show(); 

      } 
     }  
     public void onStatusChanged(String provider, int status, Bundle extras) 
     {}  
     public void onProviderEnabled(String provider) 
     {}  
     public void onProviderDisabled(String provider) 
     {} 
    };    

    Criteria criteria = new Criteria(); 
     criteria.setAccuracy(Criteria.ACCURACY_FINE); 
     // 高精度 
     criteria.setAltitudeRequired(false); 
     criteria.setBearingRequired(false); 
     criteria.setCostAllowed(true); 
     criteria.setPowerRequirement(Criteria.POWER_LOW); 
     String provider = mlocManager.getBestProvider(criteria, true); 
    mlocManager.requestLocationUpdates(provider, 2000, 0, locationListener); 
    Location loc=mlocManager.getLastKnownLocation(provider); 
    if (loc==null) 
    { 
     Log.i("loc","loc=null"); 
    } 
} 

} 

mafinest:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example.setlocaction" 
android:versionCode="1" 
android:versionName="1.0" > 
<uses-sdk 
    android:minSdkVersion="7" 
    android:targetSdkVersion="17" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.CALL_PHONE" /> 
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.RESTART_PACKAGES" /> 
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
<uses-permission android:name="android.permission.WAKE_LOCK" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name="com.example.setlocaction.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> 
</application> 

+0

發表您的清單代碼添加以下代碼在這裏 – Andrain

+0

你需要清單中允許使用的COARSE + FINE位置以及您給它的時間--2000 ms,即2秒不是e即使是NETWORK_PROVIDER也沒有。將此延遲至20000 ms,然後重試。 – g00dy

+0

@David我編輯了問題併發布了清單代碼。 – sam

回答

1

首先,當前解決方案利用「getLastKnownLocation」這意味着,如果你真的檢索經度和緯度,你不能肯定它會返回用戶的當前位置。它只是返回上次找到的位置,可以在數英里之外。

這樣做沒什麼不對,但是它會帶來不確定性。

相反,我曾親自執行的位置經理利用下面的帖子裏面的偉大工程提供的代碼檢索用戶的當前位置:

https://stackoverflow.com/a/17290348/2399772

通過使用該特定代碼,您也將獲得優勢,即它會嘗試首先使用WiFi連接來確定略好的位置。它不起作用,它會利用GPS代替。此外,如果GPS服務未啓用,將顯示一個對話框,告訴用戶啓用這些服務。

希望這會有所幫助。

其他注意事項 正如我在上一篇文章中所述,Geolocation API will does unfortunately not work on all devices。您可以在此考慮使用反向地址解析API來代替,這是另外更可靠:

https://developers.google.com/maps/documentation/geocoding/

它只是要求你送它應該包含經度和緯度,隨後其將提供響應的HTTP請求JSON很容易解析。

+0

感謝David,我在http://stackoverflow.com/a/17290348/2399772中使用了您的代碼。然而,它總是得到的經度和緯度是0.0,0.0 – sam

+0

是的,如果您在室內並使用GPS查找您的位置並且未開啓WiFi定位服務,則會發生這種情況; GPS會因此發現您的位置問題,因爲它不太可靠。 這雖然不是代碼本身的問題,但更重要的是GPS的質量。 此處的代碼似乎正常工作。嘗試打開W​​iFi定位服務並告訴我它是否有效;它通常爲我做的伎倆:) – Demitrian

+0

我已經打開wifi和3G數據,當我調試它時,不知道爲什麼LocationManager.NETWORK_PROVIDER總是返回「false」。所以我只能使用GPS。我改變了你的代碼,幸運的是它的工作。 – sam

0

有時需要一段時間的設備交付第一的位置,如果你還沒有使用GPS之前。另外,請確保您位於可以更新gps的位置,或者通過telnet使用地理修補程序嘗試模擬器。

0

試試這個

public class MyLocationActivity extends Activity implements LocationListener { 
     private LocationManager mgr; 
     private String best; 
     public static double myLocationLatitude; 
     public static double myLocationLongitude; 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 

      mgr = (LocationManager) getSystemService(LOCATION_SERVICE); 

      dumpProviders(); 

      Criteria criteria = new Criteria(); 

      best = mgr.getBestProvider(criteria, true); 
      Log.d("best provider", best); 

      Location location = mgr.getLastKnownLocation(best); 
      dumpLocation(location); 

       //may be some intent here 
     } 

     public void onLocationChanged(Location location) { 
      // TODO Auto-generated method stub 
      dumpLocation(location); 

     } 

     public void onProviderDisabled(String provider) { 
      // TODO Auto-generated method stub 

     } 

     public void onProviderEnabled(String provider) { 
      // TODO Auto-generated method stub 

     } 

     public void onStatusChanged(String provider, int status, Bundle extras) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     protected void onPause() { 

      super.onPause(); 
      mgr.removeUpdates(this); 
     } 

     @Override 
     protected void onResume() { 

      super.onResume(); 
      mgr.requestLocationUpdates(best, 15000, 1, this); 
     } 

     private void dumpLocation(Location l) { 

      if (l == null) { 

       myLocationLatitude = 0.0; 
       myLocationLongitude = 0.0; 
      } else { 

       myLocationLatitude = l.getLatitude(); 
       myLocationLongitude = l.getLongitude(); 
      } 
     } 

     private void dumpProviders() { 

      List<String> providers = mgr.getAllProviders(); 
      for (String p : providers) { 

       dumpProviders(p); 
      } 
     } 

     private void dumpProviders(String s) { 

      LocationProvider info = mgr.getProvider(s); 
      StringBuilder builder = new StringBuilder(); 
      builder.append("name: ").append(info.getName()); 
     } 

    } 
0

添加以下代碼到你的java文件

private void GetLocation() 
      { 
       LocationDetail pref_LocationDetail = new LocationDetail(_context); 
       locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

       if(objCommon.isOnline(_context)) 
       { 
        if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) 
        { 
         locationManager.requestLocationUpdates(
           LocationManager.NETWORK_PROVIDER , 
           MINIMUM_TIME_BETWEEN_UPDATES, 
           MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, 
           new MyLocationListener()  
           ); 

         return ; 
        } 
        else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) 
        { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER , 
           MINIMUM_TIME_BETWEEN_UPDATES, 
           MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, 
           new MyLocationListener()  
           ); 

         return ; 
        } 
       } 
      } 

      private class MyLocationListener implements LocationListener 
      { 

       public void onLocationChanged(Location location) 
       { 
        LocationDetail pref_LocationDetail = new LocationDetail(_context); 


         double Lattitude = location.getLatitude(); 
         double Longitude = location.getLongitude(); 



        Toast.makeText(_context , location.getProvider().toString() , Toast.LENGTH_LONG).show(); 

        locationManager.removeUpdates(this); 
        locationManager = null;                        
       } 

       public void onStatusChanged(String s, int i, Bundle b) { 
        Toast.makeText(_context , "Provider status changed", 
          Toast.LENGTH_LONG).show(); 
       } 

       public void onProviderDisabled(String s) { 
        Toast.makeText(_context , 
          "Provider disabled by the user. GPS turned off", 
          Toast.LENGTH_LONG).show();  
       } 

       public void onProviderEnabled(String s) {  
        Toast.makeText(_context , 
          "Provider enabled by the user. GPS turned on", 
          Toast.LENGTH_LONG).show(); 
       } 
      } 

只是在你的清單

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