本文共 5387 字,大约阅读时间需要 17 分钟。
1、首先允许GPS操作权限
在AndroidManifest.xml 中加入代码:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
2、其中主要应用到的知识点如下所示:
LocationManager //This class provides access to the system location services.
LocationListener //Used for receiving notifications from the LocationManager when the location has changed
Location //A class representing a geographic location sensed at a particular time (a "fix").
3、主要实现流程
1)获取LocationManager实例
2)实现监听器 LocationListener
3)注册监听器 LocationListener
4)获取地理位置信息Location
4、主要接口分析与说明
1)、android不允许直接对LocationManager进行实例化,必须通过接口getSystemService获取LocationManager实例,如:
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);。
2)、监听器的接口onLocationChanged,主要负责捕获地理位置变化后的地理位置信息。
3)、接口requestLocationUpdates注册监听器
4)、接口getLastKnownLocation返回最后一次捕获的地理位置信息数据。
5、具体实现代码
- public class gpstest extends Activity {
-
- LocationManager locationManager;
- TextView textv;
- Button btnGetLocation;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- textv=(TextView)findViewById(R.id.textview);
- btnGetLocation=(Button)findViewById(R.id.btnGetLocation);
- btnGetLocation.setOnClickListener(new bntOnClickListen());
-
-
- locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
-
-
- LocationListener locationlisten=new LocationListener() {
-
- public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
-
-
- }
-
- public void onProviderEnabled(String arg0) {
-
-
- }
-
- public void onProviderDisabled(String arg0) {
-
-
- }
-
-
- public void onLocationChanged(Location arg0) {
-
- if (arg0 != null) {
- Log.i("log", "Location changed : Lat: " + arg0.getLatitude() + " Lng: " + arg0.getLongitude());
- }
- }
- };
-
-
-
- locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationlisten);
-
- }
-
- class bntOnClickListen implements OnClickListener{
-
- public void onClick(View v) {
-
-
- Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
- if (location!=null) {
- String strLati = Double.toString(location.getLatitude());
- String strLong = Double.toString(location.getLongitude());
-
- textv.setText(strLati + "/" + strLong);
- }
- else{
- Log.i("log", "location==NULL");
- }
- }
-
- }
- }
6、GPS测试
如果是在模拟器中调试的话,有二种方法可以进行GPS测试。
第一:通过DDMS。打开"Window->Show View->Other” 中打开"Emulator Control” View即可手动设置地理位置数据,如下图所示:
![](http://hi.csdn.net/attachment/201105/23/0_1306134661M9N0.gif)
第二:使用geo命令。开始-> 运行->输入 telnet 5554,然后在命令行下输入 geo fix -39.4 116.9 326 ,这三个参数分别代表了经度、纬度和海拔(海拔可不写)。
无论是上述的那一种方法,当android捕获到地理信息之后,都会在状态栏上显示一个卫星接收的图标,如下图:
![](http://hi.csdn.net/attachment/201105/23/0_1306134914p8Mu.gif)
转载地址:http://zolvb.baihongyu.com/