如何查看 Android 设备的 GPS 是否已启用?

215
在一个启用了Android Cupcake (1.5)的设备上,如何检查并激活GPS?
在 Android Cupcake(1.5) 设备上,如何检查和激活GPS?
11个回答

471

最佳方法似乎是以下方式:

 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();
}

1
主要是关于启动一个意图来查看GPS配置,详细信息请参见http://github.com/marcust/HHPT/blob/master/src/org/thiesen/hhpt/ui/activity/main/MainActivity.java。 - Marcus
3
好的代码片段。我移除了@ SuppressWarnings,现在没有收到任何警告……也许它们不必要? - span
30
我建议在整个活动中声明alert,这样你就可以在onDestroy方法中将其解散以避免内存泄漏(if(alert != null) { alert.dismiss(); })。 - Cameron
那我如果开启省电模式,这个还能用吗? - praxmon
3
如果您的位置设置为“省电模式”,则会返回false,但 LocationManager.NETWORK_PROVIDER 会返回true。 - Tim
显示剩余3条评论

132
在安卓系统中,我们可以使用LocationManager轻松地检查设备是否启用了GPS。以下是一个简单的程序来进行检查。
GPS已启用或未启用: 请在AndroidManifest.xml中添加以下用户权限行以访问位置。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

你的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();
    }
}

输出将会是这样的

enter image description here

enter image description here


1
当我尝试你的函数时,什么也没有发生。不过在测试时我也没有收到任何错误信息。 - Airikr
我搞定了!:) 非常感谢,但在你编辑答案之前我无法投票:/ - Airikr
3
没问题,@Erik Edgren已经解决了问题,我很开心。享受吧! - user647826
@user647826:太棒了!运行得很好。你救了我的晚上。 - Addi
1
一条建议:在整个活动中声明 alert,这样您就可以在 onDestroy() 中解除它,以避免内存泄漏 (if(alert != null) { alert.dismiss(); })。 - naXa stands with Ukraine

39

是的,现在无法通过编程方式更改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
    }
如果用户想要启用GPS,则可以通过以下方式显示设置界面。
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);

在你的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
            }
        }
    }

这是一种解决方法,希望能帮到您。如果我有做错的地方,请让我知道。


2
你好,我有一个类似的问题...你能简要解释一下"REQUEST_CODE"是什么以及它的作用吗? - poeschlorn
2
@poeschlorn Anna在下面详细介绍了链接。简单来说,RequestCode允许您使用多个意图的startActivityForResult。当意图返回到您的活动时,您可以检查RequestCode以查看哪个意图正在返回并相应地做出回应。 - Farray
2
“provider” 可以是空字符串。我不得不将检查更改为 (provider != null && !provider.isEmpty()) - Pawan
由于提供者可能为空,请考虑使用以下代码: int mode = Settings.Secure.getInt(getContentResolver(),Settings.Secure.LOCATION_MODE); 如果mode=0,则GPS已关闭。 - Levon Petrosyan

33

以下是步骤:

步骤1:创建在后台运行的服务。

步骤2:您还需要在清单文件中添加以下权限:

android.permission.ACCESS_FINE_LOCATION

第三步:编写代码:

 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();

步骤 4:或者您可以简单地使用以下方法进行检查:

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

第五步:持续运行您的服务以监视连接。


6
即使关闭了GPS,它也显示GPS已启用。 - Ivan V

18

是的,你可以检查下面的代码:

public boolean isGPSEnabled (Context mContext){
    LocationManager locationManager = (LocationManager)
                mContext.getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

12

在 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()
    }

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;
};

8

这是在我的情况下起作用的代码片段

final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
    buildAlertMessageNoGps();
}

`


6

如果用户在设置中允许使用GPS,则会使用GPS。

您不再需要显式地打开它,但您也不必这样做 - 这实际上是一个隐私设置,因此您不希望进行调整。如果用户同意应用程序获取精确坐标,则会打开该功能。然后,位置管理器API将尽可能使用GPS。

如果您的应用程序没有GPS就真的没用了,并且它被关闭了,您可以使用意图打开设置应用程序到正确的屏幕,以便用户可以启用它。


5

Kotlin解决方案:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接