本代码实现GPS定位,并定时在界面上呈现定位的精度以及在用卫星数量。
布局代码如下:
<LinearLayout 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"
android:orientation="vertical" >
<TextView
android:id="@+id/showtv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="GPS经纬度获取服务,每60秒界面更新一次数据,而后台GPS更新服务是每30秒更新一次GPS数据" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="@+id/Startbtn"
android:layout_width="96dp"
android:layout_height="48dp"
android:text="@string/startbtn" />
<Button
android:id="@+id/Stopbtn"
android:layout_width="96dp"
android:layout_height="48dp"
android:text="@string/stopbtn" />
</LinearLayout>
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginTop="10dp"
android:text="@string/defaultshow"
android:textSize="18sp" />
</LinearLayout>
首先写后台的LBSServiceListener 实现LocationListener接口,在这个LBSServiceListener 中可以重写方法,代码如下:
package com.exams.demo10_lbs;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
public class LBSServiceListener implements LocationListener {
public int GPSCurrentStatus;
public Location currentLocation;
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//-------
// Called when a new location is found by the location provider.
if (currentLocation != null) {
if (isBetterLocation(location, currentLocation)) {
// Log.v("GPSTEST", "It's a better location");
currentLocation = location;
} else {
// Log.v("GPSTEST", "Not very good!");
}
} else {
// Log.v("GPSTEST", "It's first location");
currentLocation = location;
}
}
// 将数据通过get的方式发送到服务器,服务器可以根据这个数据进行跟踪用户的行走状态
private void doGet(String string) {
// TODO Auto-generated method stub
//
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
// if ((LocationManager.NETWORK_PROVIDER).equals(provider)) {
// locationManager.removeUpdates(this);
// } else if ((LocationManager.GPS_PROVIDER).equals(provider)) {
// locationManager.removeUpdates(this);
// }
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
GPSCurrentStatus = status;
}
private static final int CHECK_INTERVAL = 1000 * 30;
protected boolean isBetterLocation(Location location,
Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return t