`
yidongkaifa
  • 浏览: 4065601 次
文章分类
社区版块
存档分类
最新评论

Using the Location Manager

 
阅读更多

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);
}
分享到:
评论

相关推荐

    Introduction.to.Android.Application.Development(4th,2013.12) pdf

    Adding the Android Samples Using the SDK Manager 56 Adding the Snake Project to Your Android IDE Workspace 57 Creating an AVD for Your Snake Project 61 Creating a Launch Configuration for Your Snake...

    Joomla! 宝典.pdf

    Chapter 12: Using the Banner Manager Introducing the Banner Manager Understanding Banner Parameters Managing Clients Managing Categories Managing Banners Using the Banners Module Summary Chapter 13: ...

    Professional Android 4 Application Development 源代码

    Using the Emulator with Location-Based Services Selecting a Location Provider Finding Your Current Location Best Practice for Location Updates Using Proximity Alerts Using the Geocoder Creating Map-...

    The Android Developer’s Cookbook: Building Applications with the Android SDK

    Using location-related services such as the Google Maps API Building faster applications with native code Providing backup and restore with the Android Backup Manager Testing and debugging apps ...

    The Android Developer's Cookbook Building Applications and Source Project

    Using location-related services such as the Google Maps API Building faster applications with native code Providing backup and restore with the Android Backup Manager Testing and debugging apps ...

    数位板压力测试

    The availability of drivers that support the features of the specification will simplify the process of developing Windows appli¬cation programs that in-corporate absolute coordinate input, and ...

    professional.Android.Application.Development.2009.pdf

    Introducing the Sensor Manager 321 Using the Accelerometer and Compass 323 Introducing Accelerometers 324 Detecting Acceleration Changes 324 Creating a Speedometer 326 Determining Your ...

    Pro Android 4

    Exploring the Alarm Manager Unveiling 2D Animation Exploring Maps and Location Services Using the Telephony APIs Understanding the Media Frameworks Home Screen Widgets Home Screen List Widgets ...

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    - FIX: In "Windows ClearType" font rendering mode (OS Windows mode) the "garbage" pixels can appear from the right and from the bottom sides of the painted rectangle of the TFlexText object....

    虚拟化:管理者指南

    Storage virtualization—Allows many systems to share the same storage devices, enables concealing the location of storage systems, and more 目录: Chapter 1 A Model of Virtualization ...

    MS-DOS 5.0

    3.2 Using the Uninstall Program on an OS/2 System 4. Solving Memory Problems 4.1 386MAX 4.2 All Computers Expanded-Memory Driver 4.3 Bus Master DMA Controller 4.4 HIMEM.SYS Location 4.5 INT15 ...

    表格控件Vcl TopGrid.v3.01

    To install TopGrid components, install the following package from the [Installdir]\Lib directory using the Component|Install Packages menu selection on the Delphi menu: OSGDCLD73.BPL Installs the ...

    Pro.Android.5.1430246804

    Chapter 17 Exploring the Alarm Manager Chapter 18 Unveiling 2D Animation Chapter 19 Exploring Maps and Location Services Chapter 20 Understanding the Media Frameworks Chapter 21 Home Screen Widgets ...

    Pro.Android.5.14302468

    Chapter 17 Exploring the Alarm Manager Chapter 18 Unveiling 2D Animation Chapter 19 Exploring Maps and Location Services Chapter 20 Understanding the Media Frameworks Chapter 21 Home Screen Widgets ...

    DotNetNuke5UsersGuide (dnn5用户指南 英文原版 pdf格式)

    DotNetNukeBlogs.com, a site bringing in the best DotNetNuke blogs to one, easy-to-use location, as well as DNNVoice.com, a weekly DotNetNuke podcast. When he isn’t busy working on DotNetNuke, he can ...

    Microsoft Codeview and Utilities User's Guide

    1.5.2 Using the Enhanced Graphics Adapter's 43-Line Mode 1.5.3 Using 50-Line Mode 1.5.4 Starting with a Black-and-White Display 1.5.5 Specifying Start-Up Commands 1.5.6 Handling Interrupt Trapping ...

    一本android的好书beginning android 2 和 源码

    Report to the Manager You Make the Call! ■Chapter 35: Development Tools Hierarchical Management Delightful Dalvik Debugging Detailed, Demoed Logging File Push and Pull Screenshots Location ...

    bc940_46b_001

    Before you start implementation, make sure that you have the latest version of this document....You can find the latest version at the following location: ...

    spring-boot-reference.pdf

    13.2.2. Using Spring Boot without the Parent POM 13.2.3. Using the Spring Boot Maven Plugin 13.3. Gradle 13.4. Ant 13.5. Starters 14. Structuring Your Code 14.1. Using the “default” Package 14.2. ...

Global site tag (gtag.js) - Google Analytics