2013-03-19 101 views
0

我代碼:爲什麼不能在android設備上獲取當前位置?

Criteria cri = new Criteria(); 
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
    String tower = locationManager.getBestProvider(cri, false); 
    Location location = locationManager.getLastKnownLocation(tower); 

我的設備的Android已經打開WIFI,GPS(網絡連接使能),但位置= NULL。爲什麼?

+0

您還沒有實現監聽器。沒有返回。 – 2013-03-19 07:22:13

+0

查看MuraliGanesan的答案。 – 2013-03-19 07:22:41

+0

你會得到什麼塔? GPS或網絡? – 2013-03-19 07:33:05

回答

0

嘗試使用:

Criteria cri = new Criteria(); 
cri.setAccuracy(Criteria.ACCURACY_FINE); 
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
String tower = locationManager.getBestProvider(cri, false); 
Location location = locationManager.getLastKnownLocation(tower); 
+0

我已經添加了代碼:cri.setAccuracy(Criteria.ACCURACY_FINE);但位置仍然爲空 – 2013-03-19 07:43:45

2

試試這個,要得到下面的代碼當前位置使用。

String location; 
     LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) 
      location = LocationManager.PASSIVE_PROVIDER; 
     else 
      location = LocationManager.GPS_PROVIDER; 
     LocationListener mlocListener = new MyLocationListener(); 
     mlocManager.requestLocationUpdates(location, 0, 0, mlocListener); 
     mlocManager.requestLocationUpdates(location, 0, 1, mlocListener); 
     Location locate = mlocManager 
       .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if (locate != null) { 
      lati = locate.getLatitude(); 
      longi = locate.getLongitude(); 

     } else { 
      locate = mlocManager 
        .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); 
      if (locate != null) { 
       lati = locate.getLatitude(); 
       longi = locate.getLongitude(); 

      } 
     } 

MyLocationListener類

public class MyLocationListener implements LocationListener { 

    public void onLocationChanged(Location loc) { 
     lati = loc.getLatitude(); 
     longi = loc.getLongitude(); 

    } 

    public void onProviderDisabled(String provider) { 

    } 

    public void onProviderEnabled(String provider) { 

    } 

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

    public MainActivity getLocationCordinates() { 
     MainActivity location_Gps = new MainActivity(); 
     return location_Gps; 
    } 
} 

,添加以下權限在manifest.xml

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