Android实现>>>百度GPS定位<<<并将坐标信息上传到数据库~

本文是使用百度的定位SDK V4.2来获取安卓设备的GPS信息,因此配合百度地图使用的时候,可以直接使用坐标信息,而不用进行坐标转换。可以对比上一篇博文《Android实现>>>普通GPS定位<<<并将坐标信息上传到数据库~》来看。

百度的定位没有实现CPU叫醒功能,所以在设备锁屏后会失效,关于这点的解决,经过各种途径的探索,我使用了一个AlarmManager来解决,具体可以看下面的代码,方法不一定很好,还请各位多多指教,有好的解决方式麻烦也告诉我。

另外,关于百度定位SDK V4.2的所有问题,可以参考官方资料:http://developer.baidu.com/map/index.php?title=android-locsdk/guide/v4-2

下面进入正题,惯例,先上包结构图:


对比上一个项目,可以看出libs文件夹里多了一个armeabi文件夹(包含一个 liblocSDK4d.so 文件)和BaiduLBS_Android.jar (都是使用百度定位SDK所需)。
其中,HttpUtil.java 文件没有任何变化,内容不再列出。

首先在AndroidManifest.xml文件添加权限:(仅仅进行定位并上传的话,可能不会全用到,可以自行挑选)

<!-- 这个权限用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- 这个权限用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<!-- 获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<!-- 用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<!-- 写入扩展存储,向扩展卡写入数据,用于写入离线定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 访问网络,网络定位需要上网-->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- SD卡读取权限,用户写入离线定位数据-->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!--允许应用读取低级别的系统日志文件 -->
<uses-permission android:name="android.permission.READ_LOGS"/>  

然后在application标签里添加:

<meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="你的AK" />  
和:
<service
            android:name="com.baidu.location.f"
            android:enabled="true"
            android:process=":remote">
        </service>

<service
            android:name="com.example.gpstest.BDGpsService" >
            <intent-filter>
                <action android:name="START_LOCATING" />
            </intent-filter>
</service>

MainActivity:


package com.example.gpstest;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

private static final String LOCSTART = "START_LOCATING";
private Button startBtn;
private Button endBtn;
private Button endApp;
private TextView content;
private LocationReceiver lr;
private AlarmManager alarmManager;
private PendingIntent pi;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("MainActivity", "********MainActivity onCreate*******");
startBtn = (Button) findViewById(R.id.startServBtn);
endBtn = (Button) findViewById(R.id.endServBtn);
endApp = (Button) findViewById(R.id.endApp);
content = (TextView) findViewById(R.id.content);
alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);

startBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Log.i("MainActivity", "********MainActivity startBtn onClick*******");
Intent intent = new Intent(LOCSTART);
pi = PendingIntent.getService(getApplicationContext(), 0, intent, 
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, pi);
Toast.makeText(getApplicationContext(), "GPS测试开始", Toast.LENGTH_SHORT).show();
}
});
endBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.i("MainActivity", "********MainActivity endBtn onClick*******");
alarmManager.cancel(pi);
Intent intent = new Intent(LOCSTART);
stopService(intent);
Toast.makeText(getApplicationContext(), "GPS测试结束", Toast.LENGTH_SHORT).show();
}
});
endApp.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
android.os.Process.killProcess(android.os.Process.myPid());
}
});
lr = new LocationReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("NEW LOCATION SENT");
registerReceiver(lr, intentFilter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i("MainActivity", "********MainActivity onDestroy*******");
unregisterReceiver(lr);
}

class LocationReceiver extends BroadcastReceiver {

String locationMsg = "";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
locationMsg = intent.getStringExtra("newLoca");
content.setText(locationMsg);
}
}
}

BDGpsService:


package com.example.gpstest;

import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.example.util.BDGpsServiceListener;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class BDGpsService extends Service {

private static final int minTime = 60000;
private LocationClient locationClient;
private BDLocationListener locationListener;
private LocationClientOption lco;

@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i("BDGpsService", "********BDGpsService onCreate*******");
lco = new LocationClientOption();
lco.setLocationMode(LocationMode.Hight_Accuracy);
lco.setScanSpan(minTime);
lco.setCoorType("bd09ll");
lco.setOpenGps(true);
lco.setIsNeedAddress(true);
locationListener = new BDGpsServiceListener(getApplicationContext());
locationClient = new LocationClient(getApplicationContext());
locationClient.setLocOption(lco);
locationClient.registerLocationListener(locationListener);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.i("BDGpsService", "********BDGpsService onStartCommand*******");
if (locationClient != null && !locationClient.isStarted()){
locationClient.start();
}
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i("BDGpsService", "********BDGpsService onDestroy*******");
if (locationClient != null && locationClient.isStarted()){
locationClient.stop();
}
locationClient.unRegisterLocationListener(locationListener);
}

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}

BDGpsServiceListener:

package com.example.util;

import java.util.HashMap;
import java.util.Map;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BDGpsServiceListener implements BDLocationListener {

private Context context;

public BDGpsServiceListener(){
super();
}
public BDGpsServiceListener(Context context){
super();
this.context = context;
}

//发送广播,提示更新界面
private void sendToActivity(String str){
Intent intent = new Intent();
intent.putExtra("newLoca", str);
intent.setAction("NEW LOCATION SENT");
context.sendBroadcast(intent);
}
@Override
public void onReceiveLocation(BDLocation location) {
// TODO Auto-generated method stub
Log.i("Listener", "********BDGpsServiceListener onReceiveLocation*******");
if(location == null){return;}
StringBuffer sb = new StringBuffer();
sb.append("经度=").append(location.getLongitude());
sb.append("\n纬度=").append(location.getLatitude());
sb.append("\n时间=").append(location.getTime());
sb.append("\nERR Code=").append(location.getLocType());
if (location.hasRadius()){
sb.append("\n定位精度=").append(location.getRadius());
}
if (location.getLocType() == BDLocation.TypeGpsLocation){
sb.append("\n速度=");
sb.append(location.getSpeed());
sb.append("\n卫星=");
sb.append(location.getSatelliteNumber());
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
sb.append("\n位置=").append(location.getAddrStr());
sb.append("\n省=").append(location.getProvince());
sb.append("\n市=").append(location.getCity());
sb.append("\n区县=").append(location.getDistrict());
}

sendToActivity(sb.toString());

try {
Map<String,String> map = new HashMap<String, String>();
map.put("longi", location.getLongitude()+"");
map.put("lati", location.getLatitude()+"");
map.put("time", location.getTime());
String url = HttpUtil.BASE_URL+"coords.do?method=addCoords";
HttpUtil.postRequest(url, map);
} catch (Exception e) {
e.printStackTrace();
}
}
}

  • 1
    点赞
  • 5
    收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论 2

打赏作者

magvwiz

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值