2024年6月3日发(作者:)
本代码实现GPS定位,并定时在界面上呈现定位的精度以及在用卫星数量。
布局代码如下:
xmlns:tools="/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > android:id="@+id/showtv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="GPS经纬度获取服务,每60秒界面更新一次数据,而后台GPS更新服务是每30秒更新一次GPS数据" /> android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:gravity="center" android:orientation="horizontal" > 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" />
首先写后台的LBSServiceListener 实现LocationListener接口,在这个LBSServiceListener 中可以重写方法,代码如下:
package 10_lbs;
import rmat;
import DateFormat;
import ar;
import ianCalendar;
import ne;
import on;
import onListener;
import ;
import ;
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 ((K_PROVIDER).equals(provider)) {
// Updates(this);
// } else if ((_PROVIDER).equals(provider)) {
// Updates(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 true;
}
// Check whether the new location fix is newer or older
long timeDelta = e() - e();
boolean isSignificantlyNewer = timeDelta > CHECK_INTERVAL;
boolean isSignificantlyOlder = timeDelta < -CHECK_INTERVAL;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location,
// use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must
// be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (uracy() - currentBestLocation
.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(vider(),
vider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate
&& isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return (provider2);
}
}
这样这个LBSServiceListener已经实现,其中我使用isBetterLocation()方法对Location做判断。
下面代码是GpsSatelliteListener 实现er:
package 10_lbs;
import tus;
import er;
public class GpsSatelliteListener implements Listener {
public void onGpsStatusChanged(int event) {
// TODO Auto-generated method stub
switch (event) {
// 第一次定位
case _EVENT_FIRST_FIX:
break;
// 卫星状态改变
case _EVENT_SATELLITE_STATUS:
break;
// 定位启动
case _EVENT_STARTED:
break;
// 定位结束
case _EVENT_STOPPED:
break;
}
}
}
重点是LBSService 它是继承了Service.
在这个类中,重点通过onStartCommand方法和ACTIVITY沟通,实现将定位的经纬度等信息返回给activity的textview文本
呈现出来。
package 10_lbs;
import DateFormat;
import ;
import or;
import cation;
import cationManager;
import gIntent;
import e;
import astReceiver;
import t;
import ;
import Filter;
import ellite;
import tus;
import on;
import onListener;
import onManager;
import ;
import ;
import r;
import ;
public class LBSService extends Service {
public static final String TAG = "LBSService";
// 30000ms --minimum time interval between location updates, in milliseconds
private static final long minTime = 30000;
// 最小变更距离 10m --minimum distance between location updates, in meters
private static final float minDistance = 10;
String tag = ng();
private LocationManager locationManager;
private LocationListener locationListener;
private Location location;
private GpsStatus gStatus;
private GpsSatelliteListener gpsSatelliteListener;
private final IBinder mBinder = new LBSServiceBinder();
private NotificationManager mNM;
boolean flag;
CommandReceiver cmdReceiver;
@Override
public void onCreate() {
// TODO Auto-generated method stub
flag = true;
cmdReceiver = new CommandReceiver();
te();
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
startService();
Log.i(TAG, "in onCreate method.");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
sterReceiver(cmdReceiver);// 取消注册的CommandReceiver
roy();
stopService();
(vice);
Log.i(TAG, "in onDestroy method.");
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
IntentFilter filter = new IntentFilter();// 创建IntentFilter对象
ion("10_vice");
registerReceiver(cmdReceiver, filter);// 注册Broadcast
// Receiver,后续会接收相关广播intent
doJob();// 调用方法启动线程
return tCommand(intent, flags, startId);
}
public class LBSServiceBinder extends Binder {
LBSService getService() {
return ;
}
}
public void startService() {
locationManager = (LocationManager) getSystemService(ON_SERVICE);
locationListener = new LBSServiceListener();
tLocationUpdates(_PROVIDER,
minTime, minDistance, locationListener);
gpsSatelliteListener = new GpsSatelliteListener();
StatusListener(gpsSatelliteListener);
Log.i(TAG, "in startService method.");
}
public void stopService() {
if (locationManager != null && locationListener != null
&& gpsSatelliteListener != null) {
Updates(locationListener);
GpsStatusListener(gpsSatelliteListener);
}
Log.i(TAG, "in stopService method.");
}
private class CommandReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int cmd = Extra("cmd", -1);// 获取Extra信息
if (cmd == _STOP_SERVICE) {// 如果发来的消息是停止服务
flag = false;// 停止线程
stopSelf();// 停止服务
}
}// 继承自BroadcastReceiver的子类
}
/** * Show a notification while this service is running. */
@SuppressWarnings("deprecation")
private void showNotification() {
// In this sample, we'll use the same text
// for the ticker and the expanded
// notification
CharSequence text = getText(vice);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(_launcher,
text, tTimeMillis());
// The PendingIntent to launch our activity if the user selects this
Intent intent = new Intent(this, );
// notification
PendingIntent contentIntent = ivity(this, 0,
intent, 0);
// Set the info for the views that show in the notification panel.
estEventInfo(this, "LBSService",
"LBS Service started", contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to
// cancel.
(vice, notification);
}
// 方法:
public void doJob() {
new Thread() {
public void run() {
while (flag) {
try {// 睡眠一段时间
(60000);
} catch (Exception e) {
tackTrace();
}
Intent intent = new Intent();// 创建Intent对象
ion("10_lbs");
location = locationManager
.getLastKnownLocation(_PROVIDER);
gStatus = Status(null);
// 获取默认最大卫星数
int maxSatellites = Satellites();
Iterable
Iterator
int x = 0;
while (iterator != null && t()
&& x <= maxSatellites) {
GpsSatellite gpsSatellite = (GpsSatellite) iterator
.next();
if (Fix())
x++;
}
String latitude, longitude, accuracy, speed;
if (location != null) {
latitude = itude() + "";
longitude = gitude() + "";
accuracy = uracy() + "";
speed = ed() + "";
} else {
latitude = "0.0";
longitude = "0.0";
accuracy = "未知 ";
speed = "0.0";
}
Bundle bundle = new Bundle();
ing("latitude", latitude);
ing("longitude", longitude);
ing("accuracy", accuracy + "m");
ing("speed", speed + "m/s");
ing("Satenum", x + "个");
SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date nowDate=new Date();
String dateString=(nowDate);
ing("date", dateString+ "");
ras(bundle);
sendBroadcast(intent);// 发送广播
}
}
}.start();
}
}
最后是Activity部分:
package 10_lbs;
import ty;
import astReceiver;
import t;
import ;
import Filter;
import onManager;
import ;
import gs;
import ;
import ;
import ;
import ;
import ew;
import ;
public class MainActivity extends Activity {
public static final int CMD_STOP_SERVICE = 0;
public static final String TAG = "MainActivity";
public Button startbtnButton, stopButton;
public TextView tView;
DataReceiver dataReceiver;// BroadcastReceiver对象
public LocationManager lManager;
@Override
public void onCreate(Bundle savedInstanceState) {
te(savedInstanceState);
setContentView(ty_main);
startbtnButton = (Button) findViewById(tn);
stopButton = (Button) findViewById(n);
tView = (TextView) findViewById();
lManager = (LocationManager) getSystemService(ON_SERVICE);
// 判断GPS是否正常启动
if (!iderEnabled(_PROVIDER)) {
xt(this, "请开启GPS导航...", _SHORT).show();
// 返回开启GPS导航设置界面
Intent intent = new Intent(_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, 0);
return;
}
lickListener(new kListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startService();
}
});
lickListener(new kListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
stopService();
}
});
}
private void startService() {
bled(false);
bled(true);
Intent i = new Intent(this, );
ervice(i);
Log.i(TAG, "in startService method.");
if (dataReceiver == null) {
dataReceiver = new DataReceiver();
IntentFilter filter = new IntentFilter();// 创建IntentFilter对象
ion("10_lbs");
registerReceiver(dataReceiver, filter);// 注册Broadcast Receiver
}
}
private void stopService() {
bled(true);
bled(false);
Intent i = new Intent(this, );
rvice(i);
Log.i(TAG, "in stopService method.");
if (dataReceiver != null) {
unregisterReceiver(dataReceiver);// 取消注册Broadcast Receiver
dataReceiver = null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(ty_main, menu);
return true;
}
private class DataReceiver extends BroadcastReceiver {// 继承自BroadcastReceiver的子类
@Override
public void onReceive(Context context, Intent intent) {// 重写onReceive方法
Bundle bundledata = ras();
if (bundledata != null) {
String latitude = ing("latitude");
String longitude = ing("longitude");
String accuracy = ing("accuracy");
String speed=ing("speed");
String Satenum = ing("Satenum");
String dateString = ing("date");
t("t卫星在用数量:" + Satenum + "nt纬度:" + latitude
+ "t经度:" + longitude + "nt精度:" + accuracy
+"nt速度:"+speed+ "nt更新时间:" + dateString);
}
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
t();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
();
}
}
其中文件内容如下:
package="10_lbs" android:versionCode="1" android:versionName="1.0" > android:minSdkVersion="8" android:targetSdkVersion="15" /> android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > android:name=".MainActivity" android:label="@string/title_activity_main" > android:name=".LBSService" android:process=":remote" >


发布评论