How do I get the current GPS location programmatically in Android?

前端 未结 22 3512
梦谈多话
梦谈多话 2020-11-21 04:42

I need to get my current location using GPS programmatically. How can i achieve it?

22条回答
  •  耶瑟儿~
    2020-11-21 05:02

    For just location checking you can use following code. You can put it in your onStart() of main activity and display alert dialog if return is false.

    private boolean isLocationAccurate()
        {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
            {
                String provider = Settings.Secure
                        .getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
                if (provider != null && !provider.contains("gps"))
                {
                    return false;
                }
            }
            else
            {
                try
                {
                    int status = Settings.Secure
                            .getInt(this.getContentResolver(), Settings.Secure.LOCATION_MODE);
                    if (status != Settings.Secure.LOCATION_MODE_HIGH_ACCURACY)
                    {
                        return false;
                    }
                }
                catch (Settings.SettingNotFoundException e)
                {
                    Log.e(TAG, e.getMessage());
                }
            }
    
            return true;
        }
    

提交回复
热议问题