我正在开发一个需要打开 GPS 才能获取用户当前位置的应用。
我正在使用这段代码来检查 GPS 的当前状态:
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
然后我将进一步执行此代码:
if (!isGPSEnabled) {
// ask to turn on GPS
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "No location detected!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getBaseContext(), "first called", Toast.LENGTH_SHORT).show();
// same codes gets executed i.e. to check if user enabled GPS or not
}
});
snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);
snackbar.show();
} else {
// execute necessary code
}
上面的代码准确地检查了 GPS 的状态,但是当我再次打开 GPS 并单击 Snackbar
的“RETRY”按钮时,应该在 GPS 启动时执行的代码ON 没有执行,而是执行了 GPS OFF 时应该执行的代码。
我是否需要任何类型的接收器或任何东西来确认用户在要求他/她这样做后是否已打开 GPS?
请告诉我。
最佳答案
我在 onClick 方法中没有看到任何 if
语句,因此无论用户是否启用 GPS,它都会执行该方法中的任何内容。
如果您不介意向用户显示 Snackbar,您还可以使用广播接收器收听位置提供程序的更改。
在您的 Activity 的 onCreate 方法上:
mLocationProviderChangedReceiver = new LocalLocationProviderChangedReceiver(this);
registerReceiver(mLocationProviderChangedReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
在您的 Activity 的 onDestroy 方法上:
if (mLocationProviderChangedReceiver != null) {
unregisterReceiver(mLocationProviderChangedReceiver);
mLocationProviderChangedReceiver = null;
}
创建静态内部类:
private static class LocalLocationProviderChangedReceiver extends BroadcastReceiver {
private final WeakReference<MyActivity> mWeakActivity;
public LocalLocationProviderChangedReceiver(@NonNull MyActivity activity) {
mWeakActivity = new WeakReference<>(activity);
}
@Override
public void onReceive(Context context, Intent intent) {
MyActivity activity = mWeakActivity.get();
if (activity != null) {
activity.refresh();
}
}
}
Activity 中的刷新方法:
public void refresh() {
final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGpsEnabled) {
// TODO: Do what you need to do with the GPS
} else {
// TODO: e.g. Show a textview displaying a warning, maybe you could start the intent to activate the Location:
// Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
// startActivity(i);
}
}
关于android - 如何检查/确认用户是否开启了GPS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38852781/