如何将定位模式从默认模式更改为“高精度/省电”(仅限设备)

2024-05-10

我正在尝试使用本教程实现谷歌地图来获取当前位置

Android 谷歌地图教程 https://www.androidtutorialpoint.com/intermediate/android-map-app-showing-current-location-android/

问题是,在我启动设备的谷歌地图并授予访问谷歌位置服务的权限之前,它无法获取我当前的位置。 之后我的应用程序也获得我当前的位置。在设备中打开位置之前,它工作正常。 当位置关闭时,再次需要启动设备的谷歌地图并授予谷歌位置服务的权限。

我已经按照说明生成了密钥。

我在设备定位模式中发现了问题。当我手动将设备模式更改为高精度/省电模式时,它工作正常。

那么如何以编程方式将位置模式从默认模式(仅限设备)更改为“高精度/省电”

这是活动代码:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        }
        else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {

        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mMap.addMarker(markerOptions);

        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

        //stop location updates
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    public boolean checkLocationPermission(){
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Asking user if explanation is needed
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

                //Prompt the user once explanation has been shown
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted. Do the
                    // contacts-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }

                } else {

                    // Permission denied, Disable the functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other permissions this app might request.
            // You can add here other case statements according to your requirement.
        }
    }
}

这是清单文件代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.googlemap">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


    <permission
        android:name="com.example.envent_pc03.googlemap.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.example.googlemap.permission.MAPS_RECEIVE"/>
    <uses-feature android:name="android.hardware.location.gps" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <!--<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />-->
    <!--<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />-->
    <!--<uses-permission android:name="android.permission.INTERNET" />-->
    <!--<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />-->
    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <!--<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>-->
    <!--<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />-->

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

在请求位置更新之前,您需要根据您的要求检查位置设置是否正确。

创建一个 LocationSettingsRequest.Builder 并添加应用程序将使用的所有 LocationRequest:

 LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);

检查位置设置是否满足,使用

PendingResult<LocationSettingsResult> result =
         LocationServices.SettingsApi.checkLocationSettings(mGoogleClient, builder.build());

当 PendingResult 返回时,客户端可以通过查看 LocationSettingsResult 对象中的状态代码来检查位置设置。

 result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
     @Override
     public void onResult(LocationSettingsResult result) {
         final Status status = result.getStatus();
         final LocationSettingsStates = result.getLocationSettingsStates();
         switch (status.getStatusCode()) {
             case LocationSettingsStatusCodes.SUCCESS:
                 // All location settings are satisfied. The client can initialize location
                 // requests here.
                 ...
                 break;
             case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                 // Location settings are not satisfied. But could be fixed by showing the user
                 // a dialog.
                 try {
                     // Show the dialog by calling startResolutionForResult(),
                     // and check the result in onActivityResult().
                     status.startResolutionForResult(
                         MapsActivity.this,
                         REQUEST_CHECK_SETTINGS);
                 } catch (SendIntentException e) {
                     // Ignore the error.
                 }
                 break;
             case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                 // Location settings are not satisfied. However, we have no way to fix the
                 // settings so we won't show the dialog.
                 ...
                 break;
         }
     }
 });

对话框的结果将通过 onActivityResult(int, int, Intent) 返回

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     final LocationSettingsStates states = LocationSettingsStates.fromIntent(intent);
     switch (requestCode) {
         case REQUEST_CHECK_SETTINGS:
             switch (resultCode) {
                 case Activity.RESULT_OK:
                     // All required changes were successfully made
                     ...
                     break;
                 case Activity.RESULT_CANCELED:
                     // The user was asked to change settings, but chose not to
                     ...
                     break;
                 default:
                     break;
             }
             break;
     }
 }

作为参考,请阅读设置接口 https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi文件很好地解释了这个案例。

或者,您可以直接将用户重定向到位置设置页面。

int locationMode = Settings.Secure.getInt(activityUnderTest.getContentResolver(), Settings.Secure.LOCATION_MODE);

Check 位置模式 https://developer.android.com/reference/android/provider/Settings.Secure.html#LOCATION_MODE以获得可能的返回值。

if(locationMode == LOCATION_MODE_HIGH_ACCURACY) {
   //request location updates
} else { //redirect user to settings page
   startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将定位模式从默认模式更改为“高精度/省电”(仅限设备) 的相关文章

随机推荐

  • 将 List 作为参数传递到 postgres 的函数中

    我有这样的 Spring 数据存储库接口 public interface MyEntityRepository extends JpaRepository
  • 在 Python IDLE 会话中显示用户定义函数的列表

    是否可以在 IDLE 会话中显示所有用户功能的列表 我可以看到它们在自动完成中弹出 所以也许还有其他方法可以只显示为会话定义的用户功能 当您忘记函数名称时 它很有用 而且当您想确保在会话关闭时不会丢失函数的源代码时 这应该为您提供全局范围内
  • 成功添加具有父引用的子实体后,子实体不会显示在父资源下

    我有两个实体 书架和书籍 一个书架可以有多本书 关系是双向的 我已将这两者公开为 JpaRepositories 问题是这样的 我通过将 name sci fi 发布到 shelves 来创建一个架子 成功 我通过将 name mybook
  • 更改 UITableView 中移动单元格的默认图标

    我需要更改 UITableView 中移动单元格的默认图标 这个 是否可以 这是一个非常棘手的解决方案 可能无法长期工作 但可能会给您一个起点 重新排序控制是UITableViewCellReorderControl 但这是一个私有类 因此
  • 如何使用扩展构建双重调度

    我有一个具有类层次结构的库 如下所示 class Base class A Base class B Base 现在我想根据对象的类型 无论是 A 还是 B 做不同的事情 所以我决定去实现双重调度以避免检查类型 class ClientOf
  • 如何从 PowerQuery/Excel 数据模型中具有多对多关系的两个表中选取数据?

    这是我第一次在 stackoverflow 上提问 让我们看看进展如何 我正在尝试将不同规模资产的场景管理器连接到其所属的成本时间序列 以便我可以计算属于特定场景的资产配置的现金流 这就是我需要连接的两个表 简而言之 的样子 场景管理器 S
  • 错误:“std::this_thread”尚未声明

    我尝试使用 std this thread sleep for 函数但收到错误 error std this thread has not been declared 包括标志 GLIBCXX USE NANOSLEEP 还需要什么来强制它
  • 排除 npm 包中的测试代码?

    The 开发依赖 https docs npmjs com files package json devdependenciesnpm 的 package json 文档的部分说要在那里列出您的测试依赖项 以便您的包的用户不必拉取额外的依赖
  • Jersey 将 Weld 托管 bean 注入 ConstraintValidator

    我已经花了几个小时寻找解决方案来解决我的问题 但我无法让它发挥作用 我想将 Weld 管理的服务注入 ConstraintValidator 中 该 ConstraintValidator 用于验证发布到 JAX RS Rest Servi
  • Popper.js:点击外部时如何关闭弹出窗口

    我在用着波普尔 js https popper js org 显示具有该类的弹出元素 js share cf popover单击带有类的元素时 js share cf btn 但我希望只有当我在弹出窗口之外单击时才关闭弹出窗口 这是我显示弹
  • c++ 12位变量,我该怎么做?

    我正在构建一个体素引擎 所以我担心内存使用情况 使用 12 位而不是 16 位块 ID 可以节省大量内存 我有一个 3D 块 id 数组 每个 id 都有一个静态配置 我不确定实现这一目标的好方法是什么 有没有一种方法可以获取一块原始内存并
  • 如何让 Show 显示函数名称?

    作为一个让我熟悉 Haskell 的简单练习 在 Youtube 上闲逛并偶然进入美国倒计时游戏节目之后 我想为数字游戏制作一个求解器 你得到 6 个数字 需要将它们与 为了得到给定的结果 到目前为止我所得到的是非常脑死亡的 let ope
  • 导入属性始终为空(MEF 导入问题)

    我尝试了一段时间使用 MEF 来完成工作 但现在遇到了一个问题 我需要帮助 描述 我有 2 个 DLL 和 1 个 EXE 文件 ClassLibrary1 LoggerImpl cs SomeClass cs 类库2 ILogger cs
  • Unity Transform.LookAt 仅在一个轴上

    我一直在开发一款游戏 进展非常顺利 从这里得到了一些帮助 我再次需要它 所以我正在制作一个 2D 自上而下的射击游戏 我需要我的敌人看着玩家 显然敌人会在所有轴上旋转 因此是无敌的 或者看起来很奇怪 那么 如何让它只在Z轴上旋转呢 另外 如
  • Hibernate条件查询

    我正在尝试使用 Hibernate criteria api 执行子查询 但无法完全弄清楚如何执行它 假设有 2 个表 SHOPS 和 EMPLOYEES 其中 SHOPS 包含所有商店信息 EMPLOYEES 是所有商店中所有员工的大表
  • 为什么 FindWindow 找到了 EnumChildWindows 找不到的窗口?

    我正在寻找一个类名称为 CLIPBRDWNDCLASS 的窗口 它可以在办公应用程序和其他应用程序中找到 如果我使用 FindWindow 或 FindWindowEx 我找到第一个具有此类的 HWND 但我想要all具有该类的窗口 因此我
  • 在没有自动关闭标签的元素之前和之后插入内容

    假设我有以下内容 div content div 我想在它之前插入一些东西 注意未关闭的div content before div pre pre content div div pre content 之后还有一些 注意我现在正在关闭
  • Blazor 服务器端 Console.WriteLine 不起作用

    在服务器端 Blazor 应用程序上我发现Console WriteLine不起作用 为什么我在 Chrome 控制台中看不到该文本 code protected override async Task OnInitializedAsync
  • 在电子中播放本地mp4文件

    我正在尝试开发一个小应用程序 其中我首先通过以下方式捕获屏幕aperture包 然后尝试使用在屏幕上显示它video tag 我通过以下方式捕获屏幕 import apertureConstructor from aperture cons
  • 如何将定位模式从默认模式更改为“高精度/省电”(仅限设备)

    我正在尝试使用本教程实现谷歌地图来获取当前位置 Android 谷歌地图教程 https www androidtutorialpoint com intermediate android map app showing current l