天天看點

Android位置服務介紹,并介紹如何通過LocationManager對象擷取位置資訊



1.位置服務,英文翻譯為Location-Based Services,簡稱LBS,又稱為定位服務或基于位置的服務,融合了GPS定位、移動通信、導航等多種技術,提供與空間位置相關的綜合應用服務,基于位置的服務發展很迅速,涉及商務、醫療、工作和生活的各個方面,為使用者提供定位、追蹤和敏感區域警告等一系列服務。比如谷歌地圖,百度地圖,都需要通過位置服務。

2.Android平台下支援提供位置服務的API,在開發過程中主要用到LocationManager和LocationProviders對象:

(1).LocationManager可以用來擷取目前的位置,追蹤裝置的移動路線,或設定敏感區域,在進入或離開敏感區域時裝置會發出特定警報 。

(2).LocationProviders則是提供定位功能的元件集合,集合中的每種元件以不同的技術提供裝置的目前位置,差別在于定位的精度、速度和成本等方面 。

3.接下來将講述一個如何實作擷取位置的經緯度,并且如果位置改變,如何通過位置的改變,經緯度也發生變化的例子,這裡以LocationManager對象為例:

(1).首先,第一步,擷取LocationManager對象,可以通過調用android.app.Activity.getSystemService()函數擷取,代碼如下:

String serviceString = Context.LOCATION_SERVICE;// 擷取的是位置服務
LocationManager locationManager = (LocationManager) getSystemService(serviceString);// 調用getSystemService()方法來擷取LocationManager對象
           

其中的LOCATION_SERVICE是Android支援的系統級服務,控制位置等裝置的更新。

(2).在擷取到LocationManager對象後,還需要指定LocationManager的定位方法 ,然後才能夠調用LocationManager.getLastKnowLocation()方法擷取目前位置 ,目前LocationManager主要有兩種定位方法

GPS定位:可以提供更加精确的位置資訊,但定位速度和品質受到衛星數量和環境情況的影響,需要android.permissions.ACCESS_FINE_LOCATION使用者權限。

網絡定位:提供的位置資訊精度差,但速度較GPS定位要迅速 ,利用基站或WiFi通路的提供近似的位置資訊,需要具有如下權限:android.permission.ACCESS_COARSE_LOCATION 或 android.permission.ACCESS_FINE_LOCATION。

注:(使用GPS定位和網絡定位的LocationManager類的靜态常量不一樣,GPS定位的LocationManager類的靜态常量為:GPS_PROVIDER,網絡定位的LocationManager類的靜态常量為:NETWORK_PROVIDER,這兩個靜态常量在擷取目前位置時要用到。)

下面以使用GPS定位為例,擷取位置資訊代碼如下:

String provider = LocationManager.GPS_PROVIDER;// 指定LocationManager的定位方法
Location location = locationManager.getLastKnownLocation(provider);// 調用getLastKnownLocation()方法擷取目前的位置資訊
           

(3).通過調用Location中的getLatitude()和getLonggitude()方法可以分别擷取位置資訊中的緯度和經度,代碼如下:

double lat = location.getLatitude();//擷取緯度
double lng = location.getLongitude();//擷取經度
           

(4).在很多提供定位服務的應用程式中,不僅需要擷取目前的位置資訊,還需要監視位置的變化,在位置改變時調用特定的處理方法 ,其中LocationManager提供了一種便捷、高效的位置監視方法requestLocationUpdates(),可以根據位置的距離變化和時間間隔設定,産生位置改變事件的條件,這樣可以避免因微小的距離變化而産生大量的位置改變事件 ,LocationManager中設定監聽位置變化的代碼如下:

locationManager.requestLocationUpdates(provider, 2000, 10,locationListener);// 産生位置改變事件的條件設定為距離改變10米,時間間隔為2秒,設定監聽位置變化
           

接下來介紹上面這行代碼的各個參數,第一個參數是我們之前指定LocationManager的定位方法,GPS定位或網絡定位,第二個參數指的是産生位置改變事件的時間間隔,機關為微秒,第三個參數指的是距離條件,機關為米,第四個參數是回調函數,用于處理位置改變事件,即設定LocationListener監聽器。總的來說,那一行代碼将産生位置改變事件的條件設定為距離改變10米,時間間隔為2秒。

(5).實作locationListener的代碼如下:

private final LocationListener locationListener = new LocationListener() {

		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub

		}

	};
           

接下來對上面實作LocationListener的代碼下的四個方法進行簡單介紹:

onLocationChanged()這個方法在位置改變時被調用,onProviderDisabled()這個方法在使用者禁用具有定位功能的硬體時被調用,onProviderEnabled()這個方法在使用者啟用具有定位功能的硬體時被調用,onStatusChanged()這個方法在定位功能硬體狀态改變時被調用,例如,從不可擷取位置資訊狀态到可以擷取位置資訊的狀态,反之亦然 。

(6).為了使GPS定位功能生效,還需要在AndroidManifest.xml檔案中加入使用者許可,即加入下面這行代碼,加入使用者權限:

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

4.接下來附上完整代碼,首先建立一個Android項目,項目名稱為LocationManagerTest,建立完成後:

(1).打開activity_main.xml檔案,進行布局,布局代碼如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    
    <TextView
        android:id="@+id/location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    
</LinearLayout>
           

(2).接下來打開MainActivity.java檔案,通過LocationManager對象來擷取目前位置,代碼如下:

package xg.locationmanagertest;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		String serviceString = Context.LOCATION_SERVICE;// 擷取的是位置服務
		LocationManager locationManager = (LocationManager) getSystemService(serviceString);// 調用getSystemService()方法來擷取LocationManager
		String provider = LocationManager.GPS_PROVIDER;// 指定LocationManager的定位方法
		Location location = locationManager.getLastKnownLocation(provider);// 調用getLastKnownLocation()方法擷取目前的位置資訊
		getLocationInfo(location);// 獲得經度和緯度的方法
		locationManager.requestLocationUpdates(provider, 2000, 10,
				locationListener);// 産生位置改變事件的條件設定為距離改變10米,時間間隔為2秒,設定監聽位置變化

	}

	private void getLocationInfo(Location location) {
		String latLongInfo;
		TextView locationText = (TextView) findViewById(R.id.location);//擷取到布局檔案裡的TextView元件

		if (location != null) {
			double lat = location.getLatitude();//擷取緯度
			double lng = location.getLongitude();//擷取經度
			latLongInfo = "緯度為: " + lat + "\n經度為: " + lng;
		} else {
			latLongInfo = "沒有發現到目前位置";
		}
		locationText.setText("你目前的位置是:\n" + latLongInfo);//為TextView文本視圖指派
	}

	/*
	 * LocationListener監聽器
	 * 當位置發生改變時,會将最新的位置資訊顯示在界面上 
	 */
	private final LocationListener locationListener = new LocationListener() {

		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			getLocationInfo(location);
		}

		@Override
		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub
			getLocationInfo(null);
		}

		@Override
		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub
			getLocationInfo(null);
		}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub

		}

	};
}
           

(3).接下來再AndroidManifest.xml檔案中加入使用者權限,代碼便完成了,AndroidManifest.xml檔案代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="xg.locationmanagertest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="xg.locationmanagertest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
           

這樣即完成了代碼,就可以顯示目前位置資訊,并能夠監視裝置的位置變化 。

(4).位置服務一般都需要使用裝置上的硬體,最理想的調試方式是将程式上傳到實體裝置上運作,但在沒有實體裝置的情況下,也可以使用Android模拟器提供的虛拟方式模拟裝置的位置變化,調試具有位置服務的應用程式,這個Android模拟器提供的虛拟方式裝置在哪裡呢?

在Window菜單欄下的Show View菜單下,選擇子菜單other,彈出下圖,選擇打開下圖紅色箭頭指向處即可打開來:

Android位置服務介紹,并介紹如何通過LocationManager對象擷取位置資訊

打開DDMS中的模拟器控制,開啟Android模拟器後,在Location Controls中的Longitude和Latitude部分輸入裝置目前的經度和緯度,然後點選Send按鈕,就将虛拟的位置資訊發送到Android模拟器中,如下圖所示 :

Android位置服務介紹,并介紹如何通過LocationManager對象擷取位置資訊

運作這個項目之後,點選上圖的send按鈕,發送經緯度到Android模拟器上,效果如下:

Android位置服務介紹,并介紹如何通過LocationManager對象擷取位置資訊

如果我們把經緯度改了,改成下圖的資料,點選send按鈕:

Android位置服務介紹,并介紹如何通過LocationManager對象擷取位置資訊

然後會發現該項目裡面的經緯度變了,變成我們裝置上輸入的0和0了,如下圖所示:

Android位置服務介紹,并介紹如何通過LocationManager對象擷取位置資訊

5.以上内容僅供大家愛學習參考,這個也是我通教材上的PPT裡面學的,希望對大家有用,謝謝!