【问题标题】:How do I find out if the GPS of an Android device is enabled如何确定 Android 设备的 GPS 是否已启用
【发布时间】:2010-10-25 00:39:10
【问题描述】:

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

【问题讨论】:

  • 接受答案怎么样? :)

标签: android gps android-sensors android-1.5-cupcake


【解决方案1】:

最好的方法似乎如下:

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

【讨论】:

  • 主要是关于启动一个查看GPS配置的意图,详情见github.com/marcust/HHPT/blob/master/src/org/thiesen/hhpt/ui/…
  • 不错的sn-p代码。我删除了@SuppressWarnings 并且没有收到任何警告......也许它们是不必要的?
  • 我建议为整个活动声明 alert,以便您可以在 onDestroy 中将其关闭以避免内存泄漏 (if(alert != null) { alert.dismiss(); })
  • 如果我在省电模式下,这还能用吗?
  • @PrakharMohanSrivastava 如果您的位置设置开启了省电模式,这将返回 false,但 LocationManager.NETWORK_PROVIDER 将返回 true
【解决方案2】:

在android中,我们可以使用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();
    }
}

输出看起来像

【讨论】:

  • 当我尝试你的功能时没有任何反应。不过,我在测试时没有出错。
  • 我成功了! :) 非常感谢,但在您编辑答案之前我无法投票:/
  • 没问题@Erik Edgren,你得到了解决方案,所以我很高兴享受……!!
  • @user647826:太好了!效果很好。你拯救了我的夜晚
  • 一条建议:为整个活动声明 alert,以便您可以在 onDestroy() 中将其关闭以避免内存泄漏 (if(alert != null) { alert.dismiss(); })
【解决方案3】:

是的,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
            }
        }
    }

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

【讨论】:

  • 嗨,我有一个类似的问题...你能简单解释一下“REQUEST_CODE”是什么以及它的用途吗?
  • @poeschlorn Anna 将链接发布到下面的详细信息。简单来说,RequestCode 允许您将startActivityForResult 用于多个意图。当意图返回到您的活动时,您检查 RequestCode 以查看返回的意图并做出相应的响应。
  • provider 可以是空字符串。我不得不把支票改成(provider != null &amp;&amp; !provider.isEmpty())
  • 作为提供者可以是" ",考虑使用 int mode = Settings.Secure.getInt(getContentResolver(),Settings.Secure.LOCATION_MODE);如果 mode=0 GPS 关闭
【解决方案4】:

步骤如下:

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

第 2 步:您还需要 Manifest 文件中的以下权限:

android.permission.ACCESS_FINE_LOCATION

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

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

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

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

【讨论】:

  • 它表示即使关闭 GPS 也已启用。
【解决方案5】:

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

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

【讨论】:

    【解决方案6】:

    此方法将使用 LocationManager 服务。

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

    【讨论】:

      【解决方案7】:

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

      【讨论】:

        【解决方案8】:

        这是我的案例中的 sn-p

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

        `

        【讨论】:

          【解决方案9】:

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

          你不能再明确地打开它,但你不必这样做 - 这确实是一个隐私设置,所以你不想调整它。如果用户对获得精确坐标的应用程序感到满意,它将启用。然后位置管理器 API 将尽可能使用 GPS。

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

          【讨论】:

            【解决方案10】:

            在您的LocationListener 中,实现onProviderEnabledonProviderDisabled 事件处理程序。当您拨打requestLocationUpdates(...)时,如果手机上禁用了GPS,将拨打onProviderDisabled;如果用户启用 GPS,将调用onProviderEnabled

            【讨论】:

              【解决方案11】:

              Kotlin 解决方案:

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

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2020-09-26
                • 1970-01-01
                • 2011-11-10
                • 2016-07-07
                相关资源
                最近更新 更多