如何确定Android设备的GPS是否已启用

Mar*_*cus 199 gps android android-sensors android-1.5-cupcake

在支持Android Cupcake(1.5)的设备上,如何检查并激活GPS?

Mar*_*cus 442

最佳方式似乎如下:

 final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

    if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
        buildAlertMessageNoGps();
    }

  private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                   startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
               }
           });
    final AlertDialog alert = builder.create();
    alert.show();
}
Run Code Online (Sandbox Code Playgroud)

  • 我建议为整个活动声明`alert`,这样你就可以在onDestroy中解除它以避免内存泄漏(`if(alert!= null){alert.dismiss();}`) (29认同)
  • 很好的代码片段.我删除了@SuppressWarnings并没有收到任何警告......也许他们没有必要? (3认同)
  • @PrakharMohanSrivastava如果你的位置设置是省电的,这将返回false,但`LocationManager.NETWORK_PROVIDER`将返回true (3认同)

小智 127

在android中,我们可以使用LocationManager轻松检查设备中是否启用了GPS.

这是一个简单的检查程序.

GPS启用与否: - 将AndroidManifest.xml中的以下用户权限行添加到Access Location

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Run Code Online (Sandbox Code Playgroud)

你的java类文件应该是

public class ExampleApp extends Activity {
    /** Called when the activity is first created. */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
        }else{
            showGPSDisabledAlertToUser();
        }
    }

    private void showGPSDisabledAlertToUser(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
        .setCancelable(false)
        .setPositiveButton("Goto Settings Page To Enable GPS",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent callGPSSettingIntent = new Intent(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(callGPSSettingIntent);
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                dialog.cancel();
            }
        });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出看起来像

在此输入图像描述

在此输入图像描述

  • 没问题@Erik Edgren你得到解决方案所以我很高兴ENjoy ... !! (3认同)

ach*_*hie 37

是的GPS设置不能再以编程方式更改,因为它们是隐私设置,我们必须检查它们是否已从程序中打开并在未打开时处理它们.您可以通知用户GPS已关闭,如果需要,可以使用此类功能向用户显示设置屏幕.

检查位置提供商是否可用

    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(provider != null){
        Log.v(TAG, " Location providers: "+provider);
        //Start searching for location and update the location text when update available
        startFetchingLocation();
    }else{
        // Notify users and show settings if they want to enable GPS
    }
Run Code Online (Sandbox Code Playgroud)

如果用户想要启用GPS,您可以通过这种方式显示设置屏幕.

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);
Run Code Online (Sandbox Code Playgroud)

在onActivityResult中,您可以看到用户是否已启用它

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode == REQUEST_CODE && resultCode == 0){
            String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            if(provider != null){
                Log.v(TAG, " Location providers: "+provider);
                //Start searching for location and update the location text when update available. 
// Do whatever you want
                startFetchingLocation();
            }else{
                //Users did not switch on the GPS
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是一种方法,我希望它有所帮助.如果我做错了,请告诉我.

  • 嗨,我有类似的问题...你能简单解释一下,"REQUEST_CODE"是什么以及它的用途是什么? (2认同)
  • @poeschlorn Anna发布了以下详细链接.简单来说,RequestCode允许您使用具有多个意图的`startActivityForResult`.当意图返回到您的活动时,您检查RequestCode以查看返回的意图并相应地做出响应. (2认同)
  • `provider`可以是一个空字符串.我不得不将检查更改为`(provider!= null &&!provider.isEmpty())` (2认同)

Rak*_*esh 31

以下是步骤:

第1步:创建在后台运行的服务.

第2步:您在Manifest文件中也需要以下权限:

android.permission.ACCESS_FINE_LOCATION
Run Code Online (Sandbox Code Playgroud)

第3步:编写代码:

 final LocationManager manager = (LocationManager)context.getSystemService    (Context.LOCATION_SERVICE );

if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
  Toast.makeText(context, "GPS is disabled!", Toast.LENGTH_LONG).show(); 
else
  Toast.makeText(context, "GPS is enabled!", Toast.LENGTH_LONG).show();
Run Code Online (Sandbox Code Playgroud)

第4步:或者您只需使用以下方法检查:

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Run Code Online (Sandbox Code Playgroud)

步骤5:持续运行您的服务以监控连接.

  • 第4步,每次给我'真实',即使*GPS*没有启用.... (6认同)
  • 它告诉GPS即使关闭也会启用. (5认同)

Aru*_*mar 15

是的你可以查看以下代码:

public boolean isGPSEnabled (Context mContext){
    LocationManager locationManager = (LocationManager)
                mContext.getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*Spy 10

此方法将使用LocationManager服务。

链接

//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
    boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return statusOfGPS;
};
Run Code Online (Sandbox Code Playgroud)


小智 9

在 Kotlin 中:如何检查 GPS 是否启用

 val manager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            checkGPSEnable()
        } 

 private fun checkGPSEnable() {
        val dialogBuilder = AlertDialog.Builder(this)
        dialogBuilder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
                .setCancelable(false)
                .setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id
                    ->
                    startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))
                })
                .setNegativeButton("No", DialogInterface.OnClickListener { dialog, id ->
                    dialog.cancel()
                })
        val alert = dialogBuilder.create()
        alert.show()
    }
Run Code Online (Sandbox Code Playgroud)


小智 6

如果用户允许在其设置中使用GPS,则将使用GPS.

你不能再明确地改变它,但你不必 - 它确实是一个隐私设置,所以你不想调整它.如果用户确定应用程序获得精确的坐标,它将会打开.然后,如果可以,位置管理器API将使用GPS.

如果您的应用程序在没有GPS的情况下确实没用,并且已关闭,您可以使用意图在右侧屏幕上打开设置应用程序,以便用户可以启用它.


小智 6

这段代码检查GPS状态

final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
    buildAlertMessageNoGps();
}
Run Code Online (Sandbox Code Playgroud)

`


小智 5

科特林解决方案:

private fun locationEnabled() : Boolean {
    val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}
Run Code Online (Sandbox Code Playgroud)