在Android应用中实现GPS定位
fmms
13年前
<p>在Android开发与地理位置相关时,经常需要用到经纬度,因为这个的位置比较精确。然后可以转换成我们需要的数据。</p> <p>直接列出开发实现步骤:</p> <p>1、业务层实现,通过这个代码可以获得经纬度:</p> <pre class="brush:java; toolbar: true; auto-links: false;">package org.Base.Utils; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.widget.TextView; /** * @author coldwait * @version */ public class CoordinateHelper { public CoordinateHelper(Context context, TextView longitude, TextView latitude) { this.context = context; this.latitude = latitude; this.longitude = longitude; setLocationParam(); } double lat; double lng; private LocationManager locationManager; private Context context; private TextView longitude; private TextView latitude; public String getLatitude() { return String.valueOf(lat); } public String getLongitude() { return String.valueOf(lng); } private void setLocationParam() { try { String serviceName = Context.LOCATION_SERVICE; locationManager = (LocationManager) context .getSystemService(serviceName); /* * locationManager = * (LocationManager)getSystemService(LOCATION_SERVICE); * * String provider=LocationManager.GPS_PROVIDER; Location location = * locationManager.getLastKnownLocation(provider); */ Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); String provider = locationManager.getBestProvider(criteria, true); Location location = locationManager.getLastKnownLocation(provider); updateWithNewLocation(location); // 设置监听器,自动更新的最小时间为间隔1秒,最小位移变化超过5米 locationManager.requestLocationUpdates(provider, 1000, 5, locationListener); } catch (Exception e) { Log.e("Exception", e.getMessage()); } } private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { updateWithNewLocation(location); } public void onProviderDisabled(String provider) { updateWithNewLocation(null); } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } }; private void updateWithNewLocation(Location location) { if (location != null) { lat = location.getLatitude(); lng = location.getLongitude(); } else { lat = 0; lng = 0; } latitude.setText(getLatitude()); longitude.setText(getLongitude()); } }</pre>2、设置布局文件main.xml <pre class="brush:xml; toolbar: true; auto-links: false;"><?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/carregion" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_alignParentTop="true" android:layout_above="@+id/menu" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dip"> <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="10dip" android:paddingRight="10dip" android:stretchColumns="0,1" android:shrinkColumns="1"> <TableRow android:paddingTop="10dip" android:paddingBottom="10dip"> <TextView android:text="经度:" android:textSize="19sp" /> <TextView android:id="@+id/longitude" android:text="" android:textSize="18sp" /> </TableRow> <TableRow android:paddingTop="10dip" android:paddingBottom="10dip"> <TextView android:text="纬度:" android:textSize="19sp" /> <TextView android:id="@+id/latitude" android:text="" android:textSize="18sp" /> </TableRow> <TableRow android:paddingTop="10dip" android:paddingBottom="10dip"> <TextView android:id="@+id/pickupdata" android:text="是否采集到坐标:" android:textSize="18sp" /> <TextView android:id="@+id/ispicked" android:text="否" android:textSize="18sp" /> </TableRow> </TableLayout> </LinearLayout> </RelativeLayout></pre> <span><span>3、开发Activity文件 <pre class="brush:java; toolbar: true; auto-links: false;">public class QuestionReport extends Activity{ private TextView longitude;//设置显示经度文本框 private TextView latitude;//设置显示纬度文本框 private TextView isPicked;//设置是否捕获到经纬度 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.question_reported); location();//通过调用此成员方法,设置经纬度 } private void location() { new CoordinateHelper(this, longitude, latitude); /** * Set a special listener to be called when an action is performed on the text view. * This will be called when the enter key is pressed, or when an action supplied to the IME is selected by the user. * Setting this means that the normal hard key event will not insert a newline into the text view, even if it is multi-line; * holding down the ALT modifier will, however, allow the user to insert a newline character. * * */ latitude.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) { // TODO Auto-generated method stub return false; } }); /** * Adds a TextWatcher to the list of those whose methods are called * whenever this TextView's text changes */ latitude.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } /** * This method is called to notify you that, within s, * the count characters beginning at start have just replaced old text that had length before. * It is an error to attempt to make changes to s from this callback. */ @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub if ("0.0".equals(longitude.getText().toString()) || "".equals(longitude.getText().toString())) {//如果获取不到纬度或者得到经度为0,则显示是否获得经纬度为否 isPicked.setText("否"); } else { isPicked.setText("是"); } } }); longitude.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) { // TODO Auto-generated method stub return false; } }); longitude.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub if ("0.0".equals(longitude.getText().toString()) || "".equals(longitude.getText().toString())) {////如果获取不到经度或者得到经度为0,则显示是否获得经纬度为否 isPicked.setText("否"); } else { isPicked.setText("是"); } } }); } }</pre></span></span> <p></p> 4、为应用程序声明获取位置信息的权限 <pre class="brush:xml; toolbar: true; auto-links: false;"><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /></pre>