gpt4 book ai didi

java - 如果Android手机没有互联网连接,如何将提供商切换为GPS_provider?

转载 作者:行者123 更新时间:2023-12-02 08:08:44 25 4
gpt4 key购买 nike

我在android上制作了一个位置应用程序。这是获取纬度和经度值的代码。

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),该代码将起作用。有谁知道如何修改该代码以在 Android 手机没有任何互联网连接时自动切换到 GPS_PROVIDER 吗?谢谢

最佳答案

onLocationUpdate() 只需检查互联网是否可用,

如果互联网不可用那么,

   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 获取当前位置的精彩解释,

What is the simplest and most robust way to get the user's current location in Android?

也请引用此内容。

谢谢

关于java - 如果Android手机没有互联网连接,如何将提供商切换为GPS_provider?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7776049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com