共三个类:
第一个:MainForm.java
第二个:GpsManager.java
第三个:BGpsManager.java
第一个:MainForm.java
/**
* <br/>
* Title: MainForm.java <br/>
* E-Mail: 176291935@qq.com <br/>
* QQ: 176291935 <br/>
* Http: iaiai.iteye.com <br/>
* Create time: 2012-12-21 上午10:16:10 <br/>
* <br/>
*
* @author 丸子
* @version 0.0.1
*/
public class MainForm extends Activity {
private Context mContext = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GpsManager.getInstance().create(mContext);
BGpsManager.getInstance().create(mContext);
GpsManager.getInstance().start();
BGpsManager.getInstance().start();
int[] id1 = new int[] { R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, R.id.btn5 };
int[] id2 = new int[] { R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9, R.id.btn10 };
for (int id : id1) {
Button btn = (Button) findViewById(id);
btn.setOnClickListener(new btnGps_onClickListener());
}
for (int id : id2) {
Button btn = (Button) findViewById(id);
btn.setOnClickListener(new btnBGps_onClickListener());
}
}
private class btnGps_onClickListener implements View.OnClickListener {
public void onClick(View v) {
Button btn = (Button) v;
switch (btn.getId()) {
case R.id.btn1:
String adds = GpsManager.getInstance().getAddress();
if (null == adds || adds.length() == 0) {
Toast.makeText(mContext, "获取失败", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, adds, Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn2:
Location lt = GpsManager.getInstance().getCurrentLocation();
if (null != lt) {
Toast.makeText(mContext, String.format("维度:%f 经度:%f", lt.getLatitude(), lt.getLongitude()),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "获取失败", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn3:
GpsManager.getInstance().start();
break;
case R.id.btn4:
GpsManager.getInstance().stop();
break;
case R.id.btn5:
GpsManager.getInstance().restart();
break;
}
}
}
private class btnBGps_onClickListener implements View.OnClickListener {
public void onClick(View v) {
Button btn = (Button) v;
switch (btn.getId()) {
case R.id.btn6:
String adds = BGpsManager.getInstance().getAddress();
if (null == adds || adds.length() == 0) {
Toast.makeText(mContext, "获取失败", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, adds, Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn7:
Location lt = BGpsManager.getInstance().getCurrentLocation();
if (null != lt) {
Toast.makeText(mContext, String.format("纬度:%f 经度:%f", lt.getLatitude(), lt.getLongitude()),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "获取失败", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn8:
BGpsManager.getInstance().start();
break;
case R.id.btn9:
BGpsManager.getInstance().stop();
break;
case R.id.btn10:
BGpsManager.getInstance().restart();
break;
}
}
}
}
第二个:GpsManager.java
/**
* 通过GPS/AGPS定位(AGPS采用谷歌基站免费服务获取位置信息) <br/>
* Title: GpsManager.java <br/>
* E-Mail: 176291935@qq.com <br/>
* QQ: 176291935 <br/>
* Http: iaiai.iteye.com <br/>
* Create time: 2012-12-21 上午10:16:10 <br/>
* <br/>
*
* @author 丸子
* @version 0.0.1
*/
public class GpsManager {
private static String TAG = "GPS";
private LocationManager lm; // 位置管理
private MyLocationListener mll; // 位置监听
private Location currentLocation; // 当前位置
private Criteria ctr; // 定位标准
private String provider; // 最佳提供者
private boolean isCanceled; // 是否取消
private Context mContext;
private Handler handMessage;
private static GpsManager instance;
private GpsManager() {
}
public static GpsManager getInstance() {
if (null == instance) {
instance = new GpsManager();
}
return instance;
}
private void load() {
// 获取系统服务
lm = (LocationManager) mContext.getSystemService(Activity.LOCATION_SERVICE);
// 创建定位标准
ctr = new Criteria();
ctr.setAccuracy(Criteria.ACCURACY_FINE); // 设置精准度,待测试差距
ctr.setAltitudeRequired(false); // 设置是否返回海拔
ctr.setBearingRequired(false); // 设置是否返回方向
ctr.setCostAllowed(false); // 设置是否允许付费服务
ctr.setPowerRequirement(Criteria.POWER_HIGH); // 设置耗电等级
ctr.setSpeedRequired(false); // 设置是否返回速度信息
// 根据设置的定位条件,获取最佳provider对象,获取失败默认为GPS定位
provider = isNull(lm.getBestProvider(ctr, true), LocationManager.NETWORK_PROVIDER);
// 创建位置监听器
mll = new MyLocationListener();
// 开启GPS状态监听
new MyGpsStatusListener().start();
// 创建消息
handMessage = new HandlerMessage();
isCanceled = true;
}
/** 创建定位 */
public void create(Context mContext) {
if (null != this.mContext)
return;
this.mContext = mContext;
load();
}
/** 开始定位 */
public void start() {
handMessage.sendEmptyMessage(0);
}
/** 停止定位 */
public void stop() {
handMessage.sendEmptyMessage(1);
}
/** 重启定位 */
public void restart() {
handMessage.sendEmptyMessage(2);
}
/** 获取地址 */
public String getAddress() {
if (null == currentLocation)
return null;
StringBuffer sbAdds = new StringBuffer();
try {
// 创建地理位置编码
Geocoder gCod = new Geocoder(mContext);
List<Address> lAdds = gCod
.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
if (null == lAdds || lAdds.size() == 0 || null == lAdds.get(0))
return null;
Address adds = lAdds.get(0);
sbAdds.append(isNull(adds.getAddressLine(1), ""));
sbAdds.append(isNull(adds.getAddressLine(2), ""));
if (sbAdds.length() == 0) {
sbAdds.append(isNull(adds.getAdminArea(), ""));
sbAdds.append(isNull(adds.getLocality(), ""));
sbAdds.append(isNull(adds.getThoroughfare(), ""));
sbAdds.append(isNull(adds.getFeatureName(), ""));
}
} catch (Exception ex) {
if (null != ex && null != ex.getMessage()) {
Log.i(TAG, ex.getMessage());
}
}
return sbAdds.toString();
}
/** 获取当前位置 */
public Location getCurrentLocation() {
return currentLocation;
}
/** GPS状态监听 */
private class MyGpsStatusListener extends Thread {
public void run() {
while (true) {
try {
Thread.sleep(500);
String newProvider = isNull(lm.getBestProvider(ctr, true), LocationManager.NETWORK_PROVIDER);
// Log.i(TAG, String.format("状态:%s", newProvider));
if (!provider.equals(newProvider)) {
provider = newProvider;
restart();
}
Thread.sleep(1000);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
private class HandlerMessage extends Handler {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
// 绑定位置监听器
if (!isCanceled)
return;
lm.requestLocationUpdates(provider, 0, 0, mll);
isCanceled = false;
Log.i(TAG, "开始定位");
break;
case 1:
// 取消绑定位置监听器
if (isCanceled)
return;
lm.removeUpdates(mll);
isCanceled = true;
Log.i(TAG, "停止定位");
break;
case 2:
// 重新绑定位置监听器
if (!isCanceled) {
lm.removeUpdates(mll);
}
lm.requestLocationUpdates(provider, 0, 0, mll);
isCanceled = true;
Log.i(TAG, "重启定位");
break;
}
}
}
/** 位置监听器 */
private class MyLocationListener implements LocationListener {
// 位置发生变动时触发
public void onLocationChanged(Location location) {
currentLocation = location;
Log.i(TAG, "获取到了位置!");
}
// provider终止时调用
public void onProviderDisabled(String provider) {
}
// provider启动时调用
public void onProviderEnabled(String provider) {
}
// provider状态改变时调用
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private String isNull(String str, String defValue) {
if (null == str || str.length() == 0)
return defValue;
return str;
}
}
第三个:BGpsManager.java
/**
* 使用百度移动API进行定位 编写时间<br/>
* Title: BGpsManager.java <br/>
* E-Mail: 176291935@qq.com <br/>
* QQ: 176291935 <br/>
* Http: iaiai.iteye.com <br/>
* Create time: 2012-12-21 上午10:16:10 <br/>
* <br/>
*
* @author 丸子
* @version 0.0.1
*/
public class BGpsManager {
// 百度API授权Key,申请地址:http://dev.baidu.com/wiki/static/imap/key/
private static final String KEY = "327BC8EEE5ACB2F00811A184AB66BEC124E34EFE";
private static String TAG = "Baidu_GPS";
private BMapManager mMapManager;
private MyLocationListener mll;
private Location currentLocation; // 当前位置
private boolean isCanceled; // 是否取消
private MKSearch mSearch; // 搜素模块
private Context mContext;
private Handler handMessage;
private String address;
private static BGpsManager instance;
private BGpsManager() {
}
public static BGpsManager getInstance() {
if (null == instance) {
instance = new BGpsManager();
}
return instance;
}
private void load() {
// 创建地图管理
mMapManager = new BMapManager(mContext);
mMapManager.init(KEY, null);
mMapManager.start();
// 创建搜索
mSearch = new MKSearch();
mSearch.init(mMapManager, new MyMKSearchListener());
// 创建位置监控器
mll = new MyLocationListener();
// 创建消息
handMessage = new HandlerMessage();
isCanceled = true;
}
/** 创建定位 */
public void create(Context mContext) {
if (null != this.mContext)
return;
this.mContext = mContext;
load();
}
/** 开始定位 */
public void start() {
handMessage.sendEmptyMessage(0);
}
/** 停止定位 */
public void stop() {
handMessage.sendEmptyMessage(1);
}
/** 重启定位 */
public void restart() {
handMessage.sendEmptyMessage(2);
}
private class HandlerMessage extends Handler {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
// 绑定位置监听器
if (!isCanceled)
return;
mMapManager.getLocationManager().requestLocationUpdates(mll);
mMapManager.start();
isCanceled = false;
Log.i(TAG, "开始定位");
break;
case 1:
// 取消绑定位置监听器
if (isCanceled)
return;
mMapManager.getLocationManager().removeUpdates(mll);
mMapManager.stop();
isCanceled = true;
Log.i(TAG, "停止定位");
break;
case 2:
if (!isCanceled) {
mMapManager.getLocationManager().removeUpdates(mll);
mMapManager.stop();
}
mMapManager.getLocationManager().requestLocationUpdates(mll);
mMapManager.start();
isCanceled = false;
Log.i(TAG, "重启定位");
break;
}
}
}
/** 获取地址 */
public String getAddress() {
return address;
}
/** 获取当前位置 */
public Location getCurrentLocation() {
return currentLocation;
}
/** 位置监视器 */
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location locaiton) {
if (null != currentLocation && currentLocation.getLatitude() == locaiton.getLatitude()
&& currentLocation.getLongitude() == locaiton.getLongitude())
return;
currentLocation = locaiton;
Log.i(TAG, "获取到了位置!");
// 转换坐标为地址
mSearch.reverseGeocode(new GeoPoint((int) (locaiton.getLatitude() * 1E6),
(int) (locaiton.getLongitude() * 1E6)));
}
}
/** 搜索监视器 */
private class MyMKSearchListener implements MKSearchListener {
public void onGetAddrResult(MKAddrInfo res, int error) {
address = null;
if (error != 0)
return;
address = res.strAddr;
}
public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {
}
public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
}
public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {
}
public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
}
}
}