标签:
GPS定位貌似在室内用不了,今天自己弄了一个GPS定位小Demo,包括用户所在的经度、纬度、高度、方向、移动速度、精确度等信息。Android为GPS功能支持专门提供了一个LocationManager类,程序并不能直接创建LocationManager实例,而是通过Context的getSystemService()方法来获取。
例如:LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
下面的程序很简单,布局里面只用了一个EditText显示所有数据:
实例Demo:
MainActivity.java
package sn.qdj.localgpsdemo; import android.app.Activity; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.EditText; /** * GPS定位 * @author qingdujun * */ public class MainActivity extends Activity { LocationManager lm; EditText show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = (EditText)findViewById(R.id.show); //创建LocationManager对象 lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //从GPS获取最近的定位信息 Location lc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); //更新显示定位信息 updateView(lc); //设置每3秒 获取一次GPS定位信息 lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8, new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // 当GPS LocationProvider可用时,更新定位 updateView(lm.getLastKnownLocation(provider)); } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub updateView(null); } @Override public void onLocationChanged(Location location) { // 当GPS定位信息发生改变时,更新定位 updateView(location); } }); } public void updateView(Location newLocation){ if (newLocation != null) { StringBuilder sb = new StringBuilder(); sb.append("实时位置信息:\n"); sb.append("经度:\n"); sb.append(newLocation.getLongitude()); sb.append("\n纬度:"); sb.append(newLocation.getLatitude()); sb.append("\n高度:"); sb.append(newLocation.getAltitude()); sb.append("\n速度:"); sb.append(newLocation.getSpeed()); sb.append("\n方向:"); sb.append(newLocation.getBearing()); sb.append("\n定位精度:"); sb.append(newLocation.getAccuracy()); show.setText(sb.toString()); } else { show.setText(null); } } }
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="sn.qdj.localgpsdemo.MainActivity" > <!-- 显示定位信息 --> <EditText android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="" /> </RelativeLayout>
GPS定位需要添加一个权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
标签:
原文地址:http://www.cnblogs.com/qingdujun/p/4214244.html