我在MainActivity中有两个文件MainActivity.java和HomeFragment.java从HomeFragment调用一个函数,该函数要求用户打开手机上的位置服务.问题是即使用户已经打开了位置功能,仍然会调用该功能.有没有办法我可以这样做只有当位置功能关闭时才启动HomeFragment中的功能.
HomeFragment.java
public static void displayPromptForEnablingGPS( final Activity activity) { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS; final String message = "Enable either GPS or any other location" + " service to find current location. Click OK to go to" + " location services settings to let you do so."; builder.setMessage(message) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int id) { activity.startActivity(new Intent(action)); d.dismiss(); } }); builder.create().show(); }
MainActivity.java
public void showMainView() { HomeFragment.displayPromptForEnablingGPS(this); }
谢谢 :)
你可以使用这样的东西:
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE ); if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) { // Call your Alert message }
这应该够了吧.
要检查是否已启用位置服务,您可以使用与此类似的代码:
String locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if (locationProviders == null || locationProviders.equals("")) { ... startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); }
来源:马库斯的帖子在这里找到