Using the Location Manager

本文介绍了如何在Android应用中设置位置更新访问权限,包括在AndroidManifest中声明必要权限、获取LocationManager引用、选择合适的位置提供者及验证所选提供者是否启用等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Before your application can begin receiving location updates, it needs to perform some simple steps to set up access. In this lesson, you'll learn what these steps entail.

Declare Proper Permissions in Android Manifest

The first step of setting up location update access is to declare proper permissions in the manifest. If permissions are missing, the application will get a SecurityException at runtime.

Depending on the LocationManager methods used, either ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission is needed. For example, you need to declare the ACCESS_COARSE_LOCATION permission if your application uses a network-based location provider only. The more accurate GPS requires the ACCESS_FINE_LOCATION permission. Note that declaring the ACCESS_FINE_LOCATION permission implies ACCESS_COARSE_LOCATION already.

Also, if a network-based location provider is used in the application, you'll need to declare the internet permission as well.

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

Get a Reference to LocationManager

LocationManager is the main class through which your application can access location services on Android. Similar to other system services, a reference can be obtained from calling the getSystemService() method. If your application intends to receive location updates in the foreground (within an Activity), you should usually perform this step in the onCreate() method.

LocationManager locationManager =
        (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

Pick a Location Provider

While not required, most modern Android-powered devices can receive location updates through multiple underlying technologies, which are abstracted to an application as LocationProvider objects. Location providers may have different performance characteristics in terms of time-to-fix, accuracy, monetary cost, power consumption, and so on. Generally, a location provider with a greater accuracy, like the GPS, requires a longer fix time than a less accurate one, such as a network-based location provider.

Depending on your application's use case, you have to choose a specific location provider, or multiple providers, based on similar tradeoffs. For example, a points of interest check-in application would require higher location accuracy than say, a retail store locator where a city level location fix would suffice. The snippet below asks for a provider backed by the GPS.

LocationProvider provider =
        locationManager.getProvider(LocationManager.GPS_PROVIDER);

Alternatively, you can provide some input criteria such as accuracy, power requirement, monetary cost, and so on, and let Android decide a closest match location provider. The snippet below asks for a location provider with fine accuracy and no monetary cost. Note that the criteria may not resolve to any providers, in which case a null will be returned. Your application should be prepared to gracefully handle the situation.

// Retrieve a list of location providers that have fine accuracy, no monetary cost, etc
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(false);
...
String providerName = locManager.getBestProvider(criteria, true);

// If no suitable provider is found, null is returned.
if (providerName != null) {
   ...
}

Verify the Location Provider is Enabled

Some location providers such as the GPS can be disabled in Settings. It is good practice to check whether the desired location provider is currently enabled by calling the isProviderEnabled() method. If the location provider is disabled, you can offer the user an opportunity to enable it in Settings by firing an Intent with the ACTION_LOCATION_SOURCE_SETTINGS action.

@Override
protected void onStart() {
    super.onStart();

    // This verification should be done during onStart() because the system calls
    // this method when the user returns to the activity, which ensures the desired
    // location provider is enabled each time the activity resumes from the stopped state.
    LocationManager locationManager =
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (!gpsEnabled) {
        // Build an alert dialog here that requests that the user enable
        // the location services, then when the user clicks the "OK" button,
        // call enableLocationSettings()
    }
}

private void enableLocationSettings() {
    Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(settingsIntent);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值