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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/843675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:27:00  来源:igfitidea点击:

How do I find out if the GPS of an Android device is enabled

androidgpsandroid-sensorsandroid-1.5-cupcake

提问by Marcus

On an Android Cupcake (1.5) enabled device, how do I check and activate the GPS?

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

回答by Marcus

Best way seems to be the following:

最好的方法似乎如下:

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

回答by Marcus

In android, we can easily check whether GPS is enabled in device or not using LocationManager.

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

Here is a simple program to Check.

这是一个简单的程序来检查。

GPS Enabled or Not :- Add the below user permission line in AndroidManifest.xml to Access Location

GPS 启用与否:- 在 AndroidManifest.xml 中添加以下用户权限行以访问位置

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Your java class file should be

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

The output will looks like

输出看起来像

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

回答by achie

yes GPS settings cannot be changed programatically any more as they are privacy settings and we have to check if they are switched on or not from the program and handle it if they are not switched on. you can notify the user that GPS is turned off and use something like this to show the settings screen to the user if you want.

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

Check if location providers are available

检查位置提供程序是否可用

    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
    }

If the user want to enable GPS you may show the settings screen in this way.

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

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);

And in your onActivityResult you can see if the user has enabled it or not

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

Thats one way to do it and i hope it helps. Let me know if I am doing anything wrong.

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

回答by Rakesh

Here are the steps:

以下是步骤:

Step 1:Create services running in background.

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

Step 2:You require following permission in Manifest file too:

第 2 步:您也需要清单文件中的以下权限:

android.permission.ACCESS_FINE_LOCATION

Step 3:Write code:

第三步:编写代码:

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

Step 4:Or simply you can check using:

第 4 步:或者您可以使用以下方法进行检查:

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

Step 5:Run your services continuously to monitor connection.

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

回答by Arun kumar

Yes you can check below is the code:

是的,您可以查看以下代码:

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

回答by Code Spy

This method will use the LocationManagerservice.

此方法将使用LocationManager服务。

Source Link

链接

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

回答by kashifahmad

This piece of code checks GPS status

这段代码检查 GPS 状态

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

`

`

回答by kashifahmad

GPS will be used if the user has allowed it to be used in its settings.

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

You can't explicitly switch this on anymore, but you don't have to - it's a privacy setting really, so you don't want to tweak it. If the user is OK with apps getting precise co-ordinates it'll be on. Then the location manager API will use GPS if it can.

你不能再明确地打开它,但你不必 - 这真的是一个隐私设置,所以你不想调整它。如果用户对获得精确坐标的应用程序没有意见,它就会打开。如果可以,位置管理器 API 将使用 GPS。

If your app really isn't useful without GPS, and it's off, you can open the settings app at the right screen using an intent so the user can enable it.

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

回答by Ahmad Pourbafrani

In your LocationListener, implement onProviderEnabledand onProviderDisabledevent handlers. When you call requestLocationUpdates(...), if GPS is disabled on the phone, onProviderDisabledwill be called; if user enables GPS, onProviderEnabledwill be called.

在您的LocationListener、实施onProviderEnabledonProviderDisabled事件处理程序中。当您打电话时requestLocationUpdates(...),如果手机上禁用了 GPS,onProviderDisabled则会被呼叫;如果用户启用 GPS,onProviderEnabled将被调用。

回答by safal bhatia

In Kotlin: - How to check GPS is enable or not

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