一個最簡單的gps定出自己位置的小程序,監聽位置變化


喜歡的童鞋可以點擊下載哦:http://www.apkbus.com/android-95636-1-1.html

主程序如下:

  1 package com.ljq.activity;
  2 
  3 import java.util.Iterator;
  4 
  5 import android.app.Activity;
  6 import android.content.Context;
  7 import android.content.Intent;
  8 import android.location.Criteria;
  9 import android.location.GpsSatellite;
 10 import android.location.GpsStatus;
 11 import android.location.Location;
 12 import android.location.LocationListener;
 13 import android.location.LocationManager;
 14 import android.location.LocationProvider;
 15 import android.os.Bundle;
 16 import android.provider.Settings;
 17 import android.util.Log;
 18 import android.widget.EditText;
 19 import android.widget.Toast;
 20 
 21 public class GpsActivity extends Activity {
 22     private EditText editText;
 23     private LocationManager lm;
 24     private static final String TAG="GpsActivity"; @Override
 25  protected void onDestroy() {
 26   // TODO Auto-generated method stub
 27   super.onDestroy();
 28   lm.removeUpdates(locationListener);
 29  }
 30 
 31     @Override  
 32     protected void onPause() {   
 33         super.onPause();
 34 //        Log.e("onPause",""+(countY++));
 35         lm.removeUpdates(locationListener);   
 36     } 
 37 
 38 
 39 
 40     @Override
 41     public void onCreate(Bundle savedInstanceState) {
 42         super.onCreate(savedInstanceState);
 43         setContentView(R.layout.main);
 44         
 45         editText=(EditText)findViewById(R.id.editText);
 46         lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
 47         
 48         //判斷GPS是否正常啟動
 49         if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
 50             Toast.makeText(this, "請開啟GPS導航...", Toast.LENGTH_SHORT).show();
 51             //返回開啟GPS導航設置界面
 52             Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);   
 53             startActivityForResult(intent,0); 
 54             return;
 55         }
 56         
 57         //為獲取地理位置信息時設置查詢條件
 58         String bestProvider = lm.getBestProvider(getCriteria(), true);
 59         Log.i("out","GPS="+LocationManager.GPS_PROVIDER);
 60         Log.i("out","bestProvider="+bestProvider);
 61         //獲取位置信息
 62         //如果不設置查詢要求,getLastKnownLocation方法傳人的參數為LocationManager.GPS_PROVIDER
 63         Location location=null;
 64         while(location==null){
 65          location= lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
 66          Log.i("out","long");
 67         }
 68        
 69         updateView(location);
 70         //監聽狀態
 71 //        lm.addGpsStatusListener(listener);
 72         //綁定監聽,有4個參數    
 73         //參數1,設備:有GPS_PROVIDER和NETWORK_PROVIDER兩種
 74         //參數2,位置信息更新周期,單位毫秒    
 75         //參數3,位置變化最小距離:當位置距離變化超過此值時,將更新位置信息    
 76         //參數4,監聽    
 77         //備注:參數2和3,如果參數3不為0,則以參數3為准;參數3為0,則通過時間來定時更新;兩者為0,則隨時刷新   
 78         
 79         // 1秒更新一次,或最小位移變化超過1米更新一次;
 80         //注意:此處更新准確度非常低,推薦在service里面啟動一個Thread,在run中sleep(10000);然后執行handler.sendMessage(),更新位置
 81         lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
 82     }
 83     
 84     //位置監聽
 85     private LocationListener locationListener=new LocationListener() {
 86         
 87         /**
 88          * 位置信息變化時觸發
 89          */
 90         public void onLocationChanged(Location location) {
 91             updateView(location);
 92             Log.i(TAG, "時間:"+location.getTime()); 
 93             Log.i(TAG, "經度:"+location.getLongitude()); 
 94             Log.i(TAG, "緯度:"+location.getLatitude()); 
 95             Log.i(TAG, "海拔:"+location.getAltitude()); 
 96         }
 97         
 98         /**
 99          * GPS狀態變化時觸發
100          */
101         public void onStatusChanged(String provider, int status, Bundle extras) {
102             switch (status) {
103             //GPS狀態為可見時
104             case LocationProvider.AVAILABLE:
105                 Log.i(TAG, "當前GPS狀態為可見狀態");
106                 break;
107             //GPS狀態為服務區外時
108             case LocationProvider.OUT_OF_SERVICE:
109                 Log.i(TAG, "當前GPS狀態為服務區外狀態");
110                 break;
111             //GPS狀態為暫停服務時
112             case LocationProvider.TEMPORARILY_UNAVAILABLE:
113                 Log.i(TAG, "當前GPS狀態為暫停服務狀態");
114                 break;
115             }
116         }
117     
118         /**
119          * GPS開啟時觸發
120          */
121         public void onProviderEnabled(String provider) {
122             Location location=lm.getLastKnownLocation(provider);
123             updateView(location);
124         }
125     
126         /**
127          * GPS禁用時觸發
128          */
129         public void onProviderDisabled(String provider) {
130             updateView(null);
131         }
132 
133     
134     };
135  /*   
136     //狀態監聽
137     GpsStatus.Listener listener = new GpsStatus.Listener() {
138         public void onGpsStatusChanged(int event) {
139             switch (event) {
140             //第一次定位
141             case GpsStatus.GPS_EVENT_FIRST_FIX:
142                 Log.i(TAG, "第一次定位");
143                 break;
144             //衛星狀態改變
145             case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
146                 Log.i(TAG, "衛星狀態改變");
147                 //獲取當前狀態
148                 GpsStatus gpsStatus=lm.getGpsStatus(null);
149                 //獲取衛星顆數的默認最大值
150                 int maxSatellites = gpsStatus.getMaxSatellites();
151                 //創建一個迭代器保存所有衛星 
152                 Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
153                 int count = 0;     
154                 while (iters.hasNext() && count <= maxSatellites) {     
155                     GpsSatellite s = iters.next();     
156                     count++;     
157                 }   
158                 System.out.println("搜索到:"+count+"顆衛星");
159                 break;
160             //定位啟動
161             case GpsStatus.GPS_EVENT_STARTED:
162                 Log.i(TAG, "定位啟動");
163                 break;
164             //定位結束
165             case GpsStatus.GPS_EVENT_STOPPED:
166                 Log.i(TAG, "定位結束");
167                 break;
168             }
169         };
170     };
171  */   
172     /**
173      * 實時更新文本內容
174      * 
175      * @param location
176      */
177     private void updateView(Location location){
178         
179          Log.i("out","readyToUpdateView");
180          
181         if(location!=null){
182             Log.i("out","updateView");
183             editText.setText("設備位置信息\n\n經度:");
184             editText.append(String.valueOf(location.getLongitude()));
185             editText.append("\n緯度:");
186             editText.append(String.valueOf(location.getLatitude()));
187         }else{
188             //清空EditText對象
189              Log.i("out","null");
190             editText.getEditableText().clear();
191         }
192     }
193     
194     /**
195      * 返回查詢條件
196      * @return
197      */
198     private Criteria getCriteria(){
199         Criteria criteria=new Criteria();
200         //設置定位精確度 Criteria.ACCURACY_COARSE比較粗略,Criteria.ACCURACY_FINE則比較精細 
201         criteria.setAccuracy(Criteria.ACCURACY_FINE);    
202         //設置是否要求速度
203         criteria.setSpeedRequired(false);
204         // 設置是否允許運營商收費  
205         criteria.setCostAllowed(false);
206         //設置是否需要方位信息
207         criteria.setBearingRequired(false);
208         //設置是否需要海拔信息
209         criteria.setAltitudeRequired(false);
210         // 設置對電源的需求  
211         criteria.setPowerRequirement(Criteria.POWER_LOW);
212         return criteria;
213     }
214 }

xml文件:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="fill_parent"
 5     android:layout_height="fill_parent">
 6     <EditText android:layout_width="fill_parent"
 7         android:layout_height="wrap_content"
 8         android:cursorVisible="false"
 9         android:editable="false"
10         android:id="@+id/editText"/>
11 </LinearLayout>

記得mainfeist清單中記得添加權限:

1 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  
2 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
3 <uses-permission android:name="android.permission.INTERNET" /> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM