一个最简单的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" /> 
原文地址:https://www.cnblogs.com/xmb7/p/2905606.html