在Android應用中實現GPS定位
在Android開發與地理位置相關時,經常需要用到經緯度,因為這個的位置比較精確。然后可以轉換成我們需要的數據。
直接列出開發實現步驟:
1、業務層實現,通過這個代碼可以獲得經緯度:
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
<?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> 3、開發Activity文件
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>
4、為應用程序聲明獲取位置信息的權限<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />