android 通过GPS获取用户地理位置并监听位置变化
 1 Location Manager 管理服務
2 Location Provider 提供數據的content provider
方式一:GPS 特點:精度高,耗電量大,不耗費流量 權限<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
方式二:NETWORK 特點:精度低,省電,需要網絡訪問? 權限<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
????????????????? 或者權限<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
方式三PASSIVE_PROVIDER 資料比較少,只用于特定的情景下,SDK的解釋是,并不自己實例化去獲取地理位置,而是通過getProvider獲取其他的服務或者activity更新位置,被動的獲取更新。
操作基本步驟:
1 在manifest.xml文件中設置權限
2 獲取LocaionManager
3 選擇provider
4 創建listener
/**********************************************************************************************************************/
第一部分 權限
android的安全服務機制,如果應用要訪問本地的資源例如聯系人列表、撥號、GPS或者其他應用程序的數據,需要許可。所以要使用地理位置信息的服務需要在<manifest>標簽下添加android:name="android.permission.ACCESS_FINE_LOCATION"/>獲得許可
 也可通過單擊manifest.xml文件的permission標簽可視化的添加許可
/**********************************************************************************************************************/
第二部分? 認識LocationManager
官方SDK解釋“This class provides access to the system location services. These services allow applications to obtain periodic updates of the device's geographical location, or to fire an application-specified Intent when the device enters the proximity of a given geographical location.
You do not instantiate this class directly; instead, retrieve it through Context.getSystemService(Context.LOCATION_SERVICE). ”
翻譯一下大概意思是“LocationManager這個類提供了對系統位置服務的訪問,這些服務允許應用程序獲取設備地理位置的定期的更新,也可以在設備接近一個指定的地理位置的時候發起一個指定activity的intent。你不需要創建LocationManager的實例,取而代之的是通過Context.getSystemService(Context.LOCATION_SERVICE)獲取。”
重要的方法:來自官方SDK(附上我的翻譯注釋)
-----------------------------------------------------------------------------------------------------------------------------------------------
public Location getLastKnownLocation (String provider)
Since: API Level 1
Returns a Location indicating the data from the last known location fix obtained from the given provider. This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.
//返回一個Location,這個location標明從給定provider獲得最后已知的位置,也就是最近獲取的位置。這個操作可以不必要啟動provider,注意這個地址可能是已經過期的,例如使用的設備可能已經被關閉或者轉向了另一個位置。
 If the provider is currently disabled, null is returned.
//如果當前的provider被禁用,函數返回null
Parameters
provider ?? ?the name of the provider
Returns
??? the last known location for the provider, or null
Throws
SecurityException ?? ?if no suitable permission is present for the provider.??//前面提到的權限的問題,沒有允許會拋出安全性的異常,android系統的機制
IllegalArgumentException ?? ?if provider is null or doesn't exist????????????//非法參數異常,表示provider為null,或者不存在
------------------------------------------------------------------------------------------------------------------------------------------------
一些補充:
認識Location類
官方SDK解釋 :“A class representing a geographic location sensed at a particular time (a "fix"). A location consists of a latitude and longitude, a UTC timestamp. and optionally information on altitude, speed, and bearing.
大致的意思是:“這個類用來表示在一個特定時間被感應的地理位置信息(我們叫一個fix//感覺有點聚焦的意思,呵呵),一個location包括一個經度,緯度,一個世界時間戳還有一些關于海拔,速度和方向的可選信息。 “
 可以通過getLatitude() getLongitude() getProvider()等函數來獲取封裝信息中的經度緯度和提供信息的provider,這個比較簡單。
-----------------------------------------------------------------------------------------------------------------------------------------------
 public void requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener)
Since: API Level 1
Registers the current activity to be notified periodically by the named provider. Periodically, the supplied LocationListener will be called with the current Location or with status updates.
//注冊當前的activity定時的被provider的被通知。相當于注冊事件。每隔一段時間,LocationListenner會被調用,同時當前的位置或者狀態進行更新。
It may take a while to receive the most recent location. If an immediate location is required, applications may use the getLastKnownLocation(String) method.
//接受最新的位置信息可能會花費一會時間,如果需要立刻獲得位置信息,程序可以使用上面講的getLastKonwnLocation方法
In case the provider is disabled by the user, updates will stop, and the onProviderDisabled(String) method will be called. As soon as the provider is enabled again, the onProviderEnabled(String) method will be called and location updates will start again.
//假如provider被用戶停止,(比如關閉GPS等),更新會停止。并且onProviderDisabled方法(監聽器中一個需要復寫的方法)會被調用,只要provider再次變為可用狀態,onProviderEnable方法會被調用,并且更新操作立刻開始。
The frequency of notification may be controlled using the minTime and minDistance parameters. If minTime is greater than 0, the LocationManager could potentially rest for minTime milliseconds between location updates to conserve power. If minDistance is greater than 0, a location will only be broadcasted if the device moves by minDistance meters. To obtain notifications as frequently as possible, set both parameters to 0.
//通知(更新)的頻率可以通過使用minTime(最小更新時間 單位:毫秒)和minDistance(單位:米)參數,如果minTime大于0,LocationManager能夠在minTime時間內休息來保存電量,如果minDistance大于0,每變化這個距離就會進行一次更新,如果希望盡可能頻繁的更新的數據,則把兩個參數均設置為0.
 Background services should be careful about setting a sufficiently high minTime so that the device doesn't consume too much power by keeping the GPS or wireless radios on all the time. In particular, values under 60000ms are not recommended.
//后臺的服務應該注意,設置一個合理的minTime使得設備一直保持GPS或者WIFI的時候不耗費太多的電量。不推薦使用6000ms的minTime值
The calling thread must be a Looper thread such as the main thread of the calling Activity.
//使用該方法的線程必須時開啟消息循環的線程,例如被調用activity的主線程(可以參考Android線程機制,默認新建的線程是沒有開啟消息循環的,主線程開啟消息循環,可以參考SDK的Looper類)
Parameters
provider ?? ?the name of the provider with which to register
minTime ?? ?the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
minDistance ?? ?the minimum distance interval for notifications, in meters
listener ?? ?a {#link LocationListener} whose onLocationChanged(Location) method will be called for each location update//這是事件監聽器
Throws
IllegalArgumentException ?? ?if provider or listener is null
RuntimeException ?? ?if the calling thread has no Looper? //運行時異常,在未開啟消息循環的線程中運行
SecurityException ?? ?if no suitable permission is present for the provider.?
-----------------------------------------------------------------------------------------------------------------------------------------------
代碼如下:
 
【Based Aandroid】android 通過GPS獲取用戶地理位置并監聽位置變化
1 LocationActivity.java2 /* LocationActivity.java
3 * @author octobershiner
4 * 2011 7 22
5 * SE.HIT
6 * 一個演示定位用戶的位置并且監聽位置變化的代碼
7 * */
8 package uni.location;
9
10 import android.app.Activity;
11 import android.content.Context;
12 import android.location.Location;
13 import android.location.LocationListener;
14 import android.location.LocationManager;
15 import android.os.Bundle;
16 import android.os.Vibrator;
17 import android.util.Log;
18 import android.widget.TextView;
19
20 public class LocationActivity extends Activity {
21 /** Called when the activity is first created. */
22 //創建lcoationManager對象
23 private LocationManager manager;
24 private static final String TAG = "LOCATION DEMO";
25 @Override
26 public void onCreate(Bundle savedInstanceState) {
27 super.onCreate(savedInstanceState);
28 setContentView(R.layout.main);
29 //獲取系統的服務,
30 manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
31 Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
32 //第一次獲得設備的位置
33 updateLocation(location);
34 //重要函數,監聽數據測試
35 manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 10,
36 locationListener);
37
38 }
39 /*此處更新一下,當activity不處于活動狀態時取消GPS的監聽*/
40 public void onPause(){
41 super.onPause();
42 locationManager.removeListener(locationListener);
43 }
44
45 //創建一個事件監聽器
46 private final LocationListener locationListener = new LocationListener() {
47 public void onLocationChanged(Location location) {
48 updateLocation(location);
49 }
50 public void onProviderDisabled(String provider){
51 updateLocation(null);
52 Log.i(TAG, "Provider now is disabled..");
53 }
54 public void onProviderEnabled(String provider){
55 Log.i(TAG, "Provider now is enabled..");
56 }
57 public void onStatusChanged(String provider, int status,Bundle extras){ }
58 };
59
60 //獲取用戶位置的函數,利用Log顯示
61 private void updateLocation(Location location) {
62 String latLng;
63 if (location != null) {
64 double lat = location.getLatitude();
65 double lng = location.getLongitude();
66
67 latLng = "Latitude:" + lat + " Longitude:" + lng;
68 } else {
69 latLng = "Can't access your location";
70 }
71 Log.i(TAG, "The location has changed..");
72 Log.i(TAG, "Your Location:" +latLng);
73 }
74
75 }
只修改activity文件是不夠的,因為android系統的安全性,對服務采用授權的機制,所以需要修改manifest.xml文件
1 <?xml version="1.0" encoding="utf-8"?>2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 package="uni.location"
4 android:versionCode="1"
5 android:versionName="1.0">
6 <uses-sdk android:minSdkVersion="8" />
7
8 <application android:icon="@drawable/icon" android:label="@string/app_name">
9 <activity android:name=".LocationActivity"
10 android:label="@string/app_name">
11 <intent-filter>
12 <action android:name="android.intent.action.MAIN" />
13 <category android:name="android.intent.category.LAUNCHER" />
14 </intent-filter>
15 </activity>
16
17 </application>
18 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
19 </manifest>
 很多朋友可能會有疑問,那就是GPS定位在android虛擬機上的調試問題,其實是可以模擬的,大家啟動虛擬機,然后打開DDMS的界面,左側device欄目會動態顯示虛擬機上各項服務啟動的情況,待出虛擬機現解鎖界面后,單機device欄目下面的emulator行,這時會發現下面的emulator control下面會有 location control ,打開里面的manual標簽,哈哈相信你已經看到了經緯度,你可以更改。運行你的程序,然后單擊剛才經緯度設置的send按鈕就可以模擬接受到新的地理位置了。
在這個demo中 我用到了Log顯示狀態,推薦使用這種方法,很好用,想了解的朋友可以參考一下我的另一篇文章,學會巧妙的使用Log,跟推薦大家搜一下sundyzlh的教學視頻。
?
關于LOG的使用?單擊鏈接
最終的效果
轉載于:https://www.cnblogs.com/wuwuwu/archive/2013/05/28/6162765.html
總結
以上是生活随笔為你收集整理的android 通过GPS获取用户地理位置并监听位置变化的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 快速清空mysql表的方法
- 下一篇: 软件架构设计 导言
