Android-获取GPS数据方法

来源:互联网 发布:java中printf格式化输 编辑:程序博客网 时间:2024/06/05 15:36

Android API中提供了获取位置信息的方法,可以获取GPS的经纬度,速度,高度等。

首先通过LocationManager类来获取设备有哪些相关的位置提供商。

下面为获取位置提供商的代码:

locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);List<String> providers = locationManager.getAllProviders();ListAdapter listAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, providers);listview.setAdapter(listAdapter);
常见的位置提供商一般是GPS或passive

下面以GPS为例,获取位置信息,如经纬度,速度,高度等。

locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);updatelocation(location);//更新位置信息的方法locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000,0, new LocationListener());

其中方法requestLocationUpdates的第一参数为位置提供商,第二个参数为更新位置信息的时间间隔ms,第三个为更新位置信息的距离间隔(int)m,最后一个为位置监听对象。

我们在上面中获取了指定的位置提供商GPS的信息,并写了一个方法来用于位置的更新,而且需要为位置管理locationManager设置一个位置监听LocationListener。

重写的更新位置方法

    private void updatelocation(Location location) {        if (location != null) {            StringBuilder stringBuilder = new StringBuilder();            stringBuilder.append("实时位置信息\n");            stringBuilder.append("经度:");            stringBuilder.append(location.getLongitude());            stringBuilder.append("\n纬度:");            stringBuilder.append(location.getLatitude());            stringBuilder.append("\n高度:");            stringBuilder.append(location.getAltitude());            stringBuilder.append("\n速度:");            stringBuilder.append(location.getSpeed());            stringBuilder.append("\n时间:");            stringBuilder.append(location.getTime());            stringBuilder.append("\n精度:");            stringBuilder.append(location.getAccuracy());            stringBuilder.append("\n方位:");            stringBuilder.append(location.getBearing());            tv_gps.setText(stringBuilder.toString());        }    }


实例化LocationListener对象,需重写其中的方法,主要是

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000,0, new LocationListener() {            @Override            public void onLocationChanged(Location location) {                //当GPS位置发生改变时,更新位置                updatelocation(location);            }            @Override            public void onStatusChanged(String provider, int status, Bundle extras) {            }            @TargetApi(Build.VERSION_CODES.M)            @Override            public void onProviderEnabled(String provider) {                //当GPS PROVIDER可用时,更新位置                updatelocation(locationManager.getLastKnownLocation(provider));            }            @Override            public void onProviderDisabled(String provider) {            }        });


0 0
原创粉丝点击