![](/img/trans.png)
[英]Location from GPS_PROVIDER or NETWORK_PROVIDER in android is not consistent
[英]How to switch provider into GPS_provider if android phone doesn't have internet connection?
我在android上創建了一個位置應用程序。 這是獲取lat和long值的代碼。
public void geoLocation()
{
locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
updateWithNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {
Toast.makeText(ListenSMSservice.this,"Network Enabled",Toast.LENGTH_SHORT ).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(ListenSMSservice.this,"Network Disabled",Toast.LENGTH_SHORT ).show();
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
public void updateWithNewLocation(Location location) //update posisi terkini
{
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Geocoder gc = new Geocoder(ListenSMSservice.this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
} catch (IOException e) {}
//latLongString = "Lat:" + lat + "\nLong:" + lng;
latLongUrl="Phone Map\nhttp://maps.google.com/maps?q=" + lat + ",+" + lng + "+(Your+phone+location)&iwloc=A&hl=en\n";
} else {
latLongUrl = "No location found";
}
myMessage=latLongUrl+"\n"+addressString;
locationManager.removeUpdates(locationListener);
locationManager = null;
//Toast.makeText(ListenSMSservice.this, myMessage, 3).show();
sendsms();
}
如果我有互聯網連接( NETWORK_PROVIDER
),該代碼將有效。 有沒有人知道如何修改該代碼, GPS_PROVIDER
在Android手機沒有任何互聯網連接時自動切換到GPS_PROVIDER
? 謝謝
onLocationUpdate()
只檢查Internet是否可用,
如果Internet is not available
那么,
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
這樣,
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
return false;
}
編輯:在這里您可以找到有關Hoe的精美解釋,以獲取當前位置,
獲取用戶在Android中的當前位置的最簡單,最強大的方法是什么?
請參考這個。
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.