Android 简明教程

Android - Location Based Services

这借助 Google Play services 成为可能,它使添加位置感知与对自动位置跟踪、地理围栏和活动识别的应用程序成为可能。

This becomes possible with the help of Google Play services, which facilitates adding location awareness to your app with automated location tracking, geofencing, and activity recognition.

本教程向您展示如何在您的 APP 中使用位置服务来获取当前位置,获取定期位置更新、查找地址等。

This tutorial shows you how to use Location Services in your APP to get the current location, get periodic location updates, look up addresses etc.

The Location Object

Location 对象表示地理位置,该位置可能包括纬度、经度、时间戳以及其他信息,例如方位、高度和速度。以下是您可以使用位置对象来获取具体位置信息的重要方法 −

The Location object represents a geographic location which can consist of a latitude, longitude, time stamp, and other information such as bearing, altitude and velocity. There are following important methods which you can use with Location object to get location specific information −

Sr.No.

Method & Description

1

float distanceTo(Location dest) Returns the approximate distance in meters between this location and the given location.

2

float getAccuracy() Get the estimated accuracy of this location, in meters.

3

double getAltitude() Get the altitude if available, in meters above sea level.

4

float getBearing() Get the bearing, in degrees.

5

double getLatitude() Get the latitude, in degrees.

6

double getLongitude() Get the longitude, in degrees.

7

float getSpeed() Get the speed if it is available, in meters/second over ground.

8

boolean hasAccuracy() True if this location has an accuracy.

9

boolean hasAltitude() True if this location has an altitude.

10

boolean hasBearing() True if this location has a bearing.

11

boolean hasSpeed() True if this location has a speed.

12

void reset() Clears the contents of the location.

13

void setAccuracy(float accuracy) Set the estimated accuracy of this location, meters.

14

void setAltitude(double altitude) Set the altitude, in meters above sea level.

15

void setBearing(float bearing) Set the bearing, in degrees.

16

void setLatitude(double latitude) Set the latitude, in degrees.

17

void setLongitude(double longitude) Set the longitude, in degrees.

18

void setSpeed(float speed) Set the speed, in meters/second over ground.

19

String toString() Returns a string containing a concise, human-readable description of this object.

Get the Current Location

若要获取当前位置,请创建一个 LocationClient 对象的位置客户端,使用 connect() 方法将其连接到定位服务,然后调用其 getLastLocation() 方法。此方法将以 Location 对象的形式返回最近的位置,其中包含纬度和经度坐标及如上所述的其他信息。要在活动中获得基于位置的功能,您需要实现两个接口 −

To get the current location, create a location client which is LocationClient object, connect it to Location Services using connect() method, and then call its getLastLocation() method. This method returns the most recent location in the form of Location object that contains latitude and longitude coordinates and other information as explained above. To have location based functionality in your activity, you will have to implement two interfaces −

  1. GooglePlayServicesClient.ConnectionCallbacks

  2. GooglePlayServicesClient.OnConnectionFailedListener

这些接口提供以下重要的回调方法,您需要在活动类中实现 −

These interfaces provide following important callback methods, which you need to implement in your activity class −

Sr.No.

Callback Methods & Description

1

abstract void onConnected(Bundle connectionHint) This callback method is called when location service is connected to the location client successfully. You will use connect() method to connect to the location client.

2

abstract void onDisconnected() This callback method is called when the client is disconnected. You will use disconnect() method to disconnect from the location client.

3

abstract void onConnectionFailed(ConnectionResult result) This callback method is called when there was an error connecting the client to the service.

Get the Updated Location

如果您愿意接收位置更新,那么除了上面提到的接口之外,您还需要实现 LocationListener 接口。此接口提供了以下回调方法,您需要在活动类中实现此方法 −

If you are willing to have location updates, then apart from above mentioned interfaces, you will need to implement LocationListener interface as well. This interface provide following callback method, which you need to implement in your activity class −

Sr.No.

Callback Method & Description

1

abstract void onLocationChanged(Location location) This callback method is used for receiving notifications from the LocationClient when the location has changed.

Location Quality of Service

LocationRequest 对象用于从 LocationClient 请求位置更新的服务质量 (QoS)。以下是有用的 setter 方法,您可以使用它们来处理 QoS。有等效的 getter 方法可用,您可以在 Android 官方文档中查看这些方法。

The LocationRequest object is used to request a quality of service (QoS) for location updates from the LocationClient. There are following useful setter methods which you can use to handle QoS. There are equivalent getter methods available which you can check in Android official documentation.

Sr.No.

Method & Description

1

setExpirationDuration(long millis) Set the duration of this request, in milliseconds.

2

setExpirationTime(long millis) Set the request expiration time, in millisecond since boot.

3

setFastestInterval(long millis) Explicitly set the fastest interval for location updates, in milliseconds.

4

setInterval(long millis) Set the desired interval for active location updates, in milliseconds.

5

setNumUpdates(int numUpdates) Set the number of location updates.

6

setPriority(int priority) Set the priority of the request.

现在,例如,如果您的应用程序需要高精度的,则它应该创建一个位置请求,其中 setPriority(int) 设置为 PRIORITY_HIGH_ACCURACY 和 setInterval(long) 设置为 5 秒。您还可以使用更大的间隔和/或其他优先级,例如 PRIORITY_LOW_POWER 来请求“城市”级别精度,或 PRIORITY_BALANCED_POWER_ACCURACY 来请求“街区”级别精度。

Now for example, if your application wants high accuracy location it should create a location request with setPriority(int) set to PRIORITY_HIGH_ACCURACY and setInterval(long) to 5 seconds. You can also use bigger interval and/or other priorities like PRIORITY_LOW_POWER for to request "city" level accuracy or PRIORITY_BALANCED_POWER_ACCURACY for "block" level accuracy.

Displaying a Location Address

有了 Location 对象之后,您可以使用 Geocoder.getFromLocation() 方法获取给定纬度和经度的地址。此方法是同步的,并且可能需要很长时间才能完成其工作,因此您应该从 doInBackground() 类的方法中调用该方法。

Once you have Location object, you can use Geocoder.getFromLocation() method to get an address for a given latitude and longitude. This method is synchronous, and may take a long time to do its work, so you should call the method from the doInBackground() method of an AsyncTask class.

AsyncTask 必须是子类才能使用,并且该子类将覆盖 doInBackground(Params…​) 方法以在后台执行任务,并且 onPostExecute(Result) 方法在后台计算完成并且显示结果时在 UI 线程上调用。AyncTask 中还提供了一个更重要的方法,即 execute(Params…​ params) ,此方法使用指定的参数执行该任务。

The AsyncTask must be subclassed to be used and the subclass will override doInBackground(Params…​) method to perform a task in the background and onPostExecute(Result) method is invoked on the UI thread after the background computation finishes and at the time to display the result. There is one more important method available in AyncTask which is execute(Params…​ params), this method executes the task with the specified parameters.

Example

以下示例以实际方式向您展示如何在应用程序中使用位置服务来获取当前位置及其等效地址等。

Following example shows you in practical how to to use Location Services in your app to get the current location and its equivalent addresses etc.

Create Android Application

Step

Description

1

You will use Android studio IDE to create an Android application and name it as Tutorialspoint under a package com.example.tutorialspoint7.myapplication.

2

add src/GPSTracker.java file and add required code.

3

Modify src/MainActivity.java file and add required code as shown below to take care of getting current location and its equivalent address.

4

Modify layout XML file res/layout/activity_main.xml to add all GUI components which include three buttons and two text views to show location/address.

5

Modify res/values/strings.xml to define required constant values

6

Modify AndroidManifest.xml as shown below

7

Run the application to launch Android emulator and verify the result of the changes done in the application.

以下是修改后的主活动文件内容 MainActivity.java

Following is the content of the modified main activity file MainActivity.java.

package com.example.tutorialspoint7.myapplication;

import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.test.mock.MockPackageManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

   Button btnShowLocation;
   private static final int REQUEST_CODE_PERMISSION = 2;
   String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

   // GPSTracker class
   GPSTracker gps;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      try {
         if (ActivityCompat.checkSelfPermission(this, mPermission)
            != MockPackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{mPermission},
               REQUEST_CODE_PERMISSION);

            // If any permission above not allowed by user, this condition will
               execute every time, else your else part will work
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      btnShowLocation = (Button) findViewById(R.id.button);

      // show location button click event
      btnShowLocation.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
            // create class object
            gps = new GPSTracker(MainActivity.this);

            // check if GPS enabled
            if(gps.canGetLocation()){

               double latitude = gps.getLatitude();
               double longitude = gps.getLongitude();

               // \n is for new line
               Toast.makeText(getApplicationContext(), "Your Location is - \nLat: "
                  + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
            }else{
               // can't get location
               // GPS or Network is not enabled
               // Ask user to enable GPS/network in settings
               gps.showSettingsAlert();
            }

         }
      });
   }
}

以下是已修改主活动文件 GPSTracker.java 的内容。

Following is the content of the modified main activity file GPSTracker.java.

package com.example.tutorialspoint7.myapplication;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

   private final Context mContext;

   // flag for GPS status
   boolean isGPSEnabled = false;

   // flag for network status
   boolean isNetworkEnabled = false;

   // flag for GPS status
   boolean canGetLocation = false;

   Location location; // location
   double latitude; // latitude
   double longitude; // longitude

   // The minimum distance to change Updates in meters
   private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

   // The minimum time between updates in milliseconds
   private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

   // Declaring a Location Manager
   protected LocationManager locationManager;

   public GPSTracker(Context context) {
      this.mContext = context;
      getLocation();
   }

   public Location getLocation() {
      try {
         locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

         // getting GPS status
         isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

         // getting network status
         isNetworkEnabled = locationManager
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

         if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
         } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
               locationManager.requestLocationUpdates(
                  LocationManager.NETWORK_PROVIDER,
                  MIN_TIME_BW_UPDATES,
                  MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

               Log.d("Network", "Network");
               if (locationManager != null) {
                  location = locationManager
                     .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                  if (location != null) {
                     latitude = location.getLatitude();
                     longitude = location.getLongitude();
                  }
               }
            }

            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
               if (location == null) {
                  locationManager.requestLocationUpdates(
                     LocationManager.GPS_PROVIDER,
                     MIN_TIME_BW_UPDATES,
                     MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                  Log.d("GPS Enabled", "GPS Enabled");
                  if (locationManager != null) {
                     location = locationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);

                     if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                     }
                  }
               }
            }
         }

      } catch (Exception e) {
         e.printStackTrace();
      }

      return location;
   }

   /**
      * Stop using GPS listener
      * Calling this function will stop using GPS in your app
   * */

   public void stopUsingGPS(){
      if(locationManager != null){
         locationManager.removeUpdates(GPSTracker.this);
      }
   }

   /**
      * Function to get latitude
   * */

   public double getLatitude(){
      if(location != null){
         latitude = location.getLatitude();
      }

      // return latitude
      return latitude;
   }

   /**
      * Function to get longitude
   * */

   public double getLongitude(){
      if(location != null){
         longitude = location.getLongitude();
      }

      // return longitude
      return longitude;
   }

   /**
      * Function to check GPS/wifi enabled
      * @return boolean
   * */

   public boolean canGetLocation() {
      return this.canGetLocation;
   }

   /**
      * Function to show settings alert dialog
      * On pressing Settings button will lauch Settings Options
   * */

   public void showSettingsAlert(){
      AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

      // Setting Dialog Title
      alertDialog.setTitle("GPS is settings");

      // Setting Dialog Message
      alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

      // On pressing Settings button
      alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
         }
      });

      // on pressing cancel button
      alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
         }
      });

      // Showing Alert Message
      alertDialog.show();
   }

   @Override
   public void onLocationChanged(Location location) {
   }

   @Override
   public void onProviderDisabled(String provider) {
   }

   @Override
   public void onProviderEnabled(String provider) {
   }

   @Override
   public void onStatusChanged(String provider, int status, Bundle extras) {
   }

   @Override
   public IBinder onBind(Intent arg0) {
      return null;
   }
}

以下是 res/layout/activity_main.xml 文件的内容——

Following will be the content of res/layout/activity_main.xml file −

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:layout_width = "fill_parent"
   android:layout_height = "fill_parent"
   android:orientation = "vertical" >


   <Button
      android:id = "@+id/button"
      android:layout_width = "fill_parent"
      android:layout_height = "wrap_content"
      android:text = "getlocation"/>

</LinearLayout>

以下是 res/values/strings.xml 的内容,用于定义两个新常量——

Following will be the content of res/values/strings.xml to define two new constants −

<?xml version = "1.0" encoding = "utf-8"?>
<resources>
   <string name = "app_name">Tutorialspoint</string>
</resources>

以下是 AndroidManifest.xml 的默认内容−

Following is the default content of AndroidManifest.xml

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
   package = "com.example.tutorialspoint7.myapplication">
   <uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name = "android.permission.INTERNET" />
   <application
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">

      <activity android:name = ".MainActivity">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />

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

</manifest>

我们尝试运行您的 Tutorialspoint 应用程序。我假设,您已将您的安卓移动设备连接到您的电脑。要从 Android Studio 运行应用程序,请打开您项目的某个活动文件,然后从工具栏中点击运行图标。在启动您的应用程序之前,Android Studio 安装程序将显示以下窗口,供您选择运行安卓应用程序的位置。

Let’s try to run your Tutorialspoint application. I assume that, you have connected your actual Android Mobile device with your computer. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application.

location3

现在查看位置,点击获取位置按钮将显示位置信息,如下所示:

Now to see location select Get Location Button which will display location information as follows −

location4