首页 > 其他分享 >用百度SDK获取地理位置和天气信息

用百度SDK获取地理位置和天气信息

时间:2022-12-06 10:00:13浏览次数:57  
标签:定位 bdLocation 地理位置 location msg import null 百度 SDK


下面实现通过百度SDK获取地理位置和天气信息,请参考​​百度开发文档​

1. 在​​相关下载​​最新的库文件。将so文件的压缩文件解压出来,把对应架构下的so文件放入开发者自己APP的对应架构下的文件夹中,建议全部放入, 程序兼容性会大大提升,将locSDK_5.X.jar文件拷贝到工程的libs目录下,这样您就可以在程序中使用百度定位SDK了。

2. 设置AndroidManifest.xml

在application标签中声明service组件,每个app拥有自己单独的定位service


<service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote">
</service>


【重要提醒】

定位SDKv3.1版本之后,以下权限已不需要,请取消声明,否则将由于Android 5.0多帐户系统加强权限管理而导致应用安装失败。

<uses-permission android:name="android.permission.BAIDU_LOCATION_SERVICE"></uses-permission>

3.声明使用权限

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

设置AcessKey

使用SDK5.0需要在Mainfest.xml设置Accesskey,设置有误会引起定位和地理围栏服务不能正常使用,必须进行Accesskey的正确设置。

设置AccessKey,在application标签中加入


<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="key" /> //key:开发者申请的key


相关功能类的使用,请参看百度开发文档,附上自己写的获取地理位置和天气 LocationService.java:

package com.lenovo.realvideocamera.service;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.lenovo.realvideocamera.R;
import com.lenovo.realvideocamera.util.DateUtil;
import com.lenovo.realvideocamera.util.FileUtil;
import com.lenovo.realvideocamera.util.HttpUtil;
import com.lenovo.realvideocamera.util.ImageUtil;

/**
* 地理位置、天气Service
* @author Jackie
*
*/
public class LocationService extends Service implements BDLocationListener {

private String TAG = "LocationService";

public LocationClient locationClient; //百度地图定位Client
private BDLocation bdLocation; //百度地图定位信息
private Bitmap weatherBitmap; //天气缩略图bitmap

@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind");
return null;
}

@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");
}

@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(TAG, "onStart");
initLocation();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
if (locationClient != null) {
locationClient.stop();
}
super.onDestroy();
}

/**
* @author Jackie
* 百度地图定位初始化
*/
private void initLocation() {
locationClient = new LocationClient(this);
locationClient.registerLocationListener(this); //设置地图定位回调监听

LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationMode.Hight_Accuracy);//设置定位模式 Hight_Accuracy高精度、Battery_Saving低功耗、Device_Sensors仅设备(GPS)
option.setCoorType("gcj02");//返回的定位结果是百度经纬度,默认值gcj02 国测局经纬度坐标系gcj02、百度墨卡托坐标系bd09、百度经纬度坐标系bd09ll
option.setIsNeedAddress(true);//返回的定位结果包含地址信息
//option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms 不设置或设置数值小于1000ms标识只定位一次
//option.setNeedDeviceDirect(true);//返回的定位结果包含手机机头的方向
locationClient.setLocOption(option);

locationClient.start();
}

@Override
public void onReceiveLocation(BDLocation location) {
if (null == location) {
if (bdLocation != null) {
bdLocation = null;
}
Log.d(TAG, "定位失败:location is null");
return;
}
/**
* 61 : GPS定位结果
* 62 : 扫描整合定位依据失败。此时定位结果无效。
* 63 : 网络异常,没有成功向服务器发起请求。此时定位结果无效。
* 65 : 定位缓存的结果。
* 66 : 离线定位结果。通过requestOfflineLocaiton调用时对应的返回结果
* 67 : 离线定位失败。通过requestOfflineLocaiton调用时对应的返回结果
* 68 : 网络连接失败时,查找本地离线定位时对应的返回结果
* 161: 表示网络定位结果
* 162~167: 服务端定位失败
* 502:key参数错误
* 505:key不存在或者非法
* 601:key服务被开发者自己禁用
* 602:key mcode不匹配
* 501~700:key验证失败
*/
int code = location.getLocType();
if (code == 161) {
this.bdLocation = location;
String city = location.getCity();
double latitude = location.getLatitude();
double lontitude = location.getLongitude();
String address = location.getAddrStr();
Log.d(TAG, "city " + city + ",(latitude,lontitude) (" + latitude + "," + lontitude + "),address " + address);
requestWeather();
} else {
if (bdLocation != null) {
bdLocation = null;
}
Log.d(TAG, "定位失败:code=" + code);
}
}

/**
*
* @author Jackie
* 获取天气
*
* @param view
*/
@SuppressLint("HandlerLeak")
private void requestWeather() {
final Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg == null) {
return;
}
JSONObject object = (JSONObject) msg.obj;
try {
int code = object.getInt("error");
String states = object.getString("status");
if (code == 0 && states.equals("success")) {
JSONArray results = object.getJSONArray("results");
JSONObject resultObj = results.getJSONObject(0);
JSONArray weatherArray = resultObj.getJSONArray("weather_data");
JSONObject weatherObj = weatherArray.getJSONObject(0);

String dayPictureUrl = weatherObj.getString("dayPictureUrl");
String nightPictureUrl = weatherObj.getString("nightPictureUrl");

//TODO 增加日间、夜间的判断
int tag = DateUtil.judgeAmOrPm();
if (tag == 0) { //上午
getWeatherBitmap(dayPictureUrl);
} else { //下午
getWeatherBitmap(nightPictureUrl);
}
} else {
Log.d(TAG, "天气信息获取失败,code=" + code);
}
} catch (JSONException e) {
Log.d(TAG, "天气信息Json解析错误");
e.printStackTrace();
}
super.handleMessage(msg);
}
};

new Thread(new Runnable() {
public void run() {
JSONObject result = getWeatherJson();
Message msg = Message.obtain();
msg.obj = result;
myHandler.sendMessage(msg);
}

private JSONObject getWeatherJson() {
// TODO location获取成功调用requestWeather 所以不存在location为空的情况
String city = bdLocation.getCity();
if (city.contains("市")) {
city.replace("市", "");
}
//拼凑百度天气请求的完整url
StringBuffer url = new StringBuffer();
url.append(getString(R.string.url_weather));
url.append(city);
url.append("&output=json&ak=");
url.append(getString(R.string.baidu_server_key));
return HttpUtil.getJsonObjectResult(url.toString(), null);
}
}).start();
}

/**
* 获取图片url对应的bitmap
* @return
*/
@SuppressLint("HandlerLeak")
private void getWeatherBitmap(final String url) {
final Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg == null) {
return;
}
weatherBitmap = (Bitmap) msg.obj;
Log.d(TAG, "weatherBitmap convert ok!");

mergeBitmap();
super.handleMessage(msg);
stopSelf();
}
};

new Thread(new Runnable() {
public void run() {
Bitmap bitmap = ImageUtil.getNetImage(url, 1);

Message msg = Message.obtain();
msg.obj = bitmap;
myHandler.sendMessage(msg);
}
}).start();
}

private String fileName = "location_weather.jpg";

/**
* 合并天气、地理位置为bitmap
* @param bitmap
* @param str
* @return
*/
private Bitmap mergeBitmap() {
if (bdLocation == null && weatherBitmap == null) {
return null;
}

Bitmap mergeBitmap = null;
if (bdLocation != null && weatherBitmap != null) {
mergeBitmap = ImageUtil.mergeBitmap(this, weatherBitmap, TextUtils.isEmpty(bdLocation.getAddrStr())?"":bdLocation.getAddrStr());
} else if (bdLocation != null){
mergeBitmap = ImageUtil.convertFontBitmap(this, TextUtils.isEmpty(bdLocation.getAddrStr())?"":bdLocation.getAddrStr());
}
// save 操作
//String filePath = FileUtil.saveBitmap(fileName, mergeBitmap);
String filePath = FileUtil.saveBitmap(fileName, mergeBitmap);

//Intent intent = new Intent(getString(R.string.location_receiver));
//intent.putExtra("mergeBitmap", mergeBitmap);
//intent.putExtra("fileName", fileName);
//getApplication().sendBroadcast(intent);

SharedPreferences mSharedPreferences = getSharedPreferences("real_video_camera", 0);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putString(getString(R.string.key_location_file_path), filePath);
mEditor.commit();

Log.d(TAG, "mergeBitmap ok");

return mergeBitmap;
}

}


标签:定位,bdLocation,地理位置,location,msg,import,null,百度,SDK
From: https://blog.51cto.com/u_11407799/5914596

相关文章

  • ArcObjects SDK开发 011 RasterLayer
    1、RasterLayer的结构图层的话,除了FeatureLayer外,用的最多的就是RasterLayer了。较FeatureLayer而言,RasterLayer比较简单,这点可以从栅格图层的属性对话框中可以看出。其......
  • 美颜SDK滤镜功能有哪些常用的滤镜算法
    “美颜滤镜”,可以说是美颜SDK中大家最常用到的一个功能,几乎所有的主播和个人用户都曾经使用过此功能。但是,如果要追溯滤镜的发展史,那得把目光转向至很久之前。最开始的时候,......
  • Win10下SDK Manager应用程序闪退问题的解决方法
    SDKManager闪退原因:未找到Java的正确路径解决办法:1、在压缩包中找到Android.bat文件,右键编辑2、打开的Android文件内容,找到如图的几行代码将上面的代码替换成:其中......
  • 【python】使用百度api进行音频文件转写
     【python】使用百度api进行音频文件转写脚本目标:智能云的音频文件转写文档只给了个demo,每次只能传1分钟以内的音频啥的,不好直接用,简单打包一下,做到把音频放文件夹,直......
  • HyperLedger/Fabric 快速上手优化版 fabric-sdk-java
    文章目录​​1.前言​​​​2.前置条件​​​​3.区块链网络修改​​​​4.SDK操作步骤​​​​5.transaction.proto​​​​6.相关网址​​1.前言   由于fabri......
  • fabric sdk简介
    SourceURL:file:///media/john/disk-500G/备份/桌面/监控技术预研结果.dochttps://hyperledger.github.io/fabric-sdk-node/     https://github.com/hyperled......
  • Isaac SDK & Sim 环境
    Isaac是NVIDIA开放的机器人平台。其IsaacSDK包括以下内容:IsaacApps:各种机器人应用示例,突出Engine特性或专注GEM功能IsaacEngine:一个软件框架,可轻松构建......
  • 百度离线ocr在提交git后再拉代码,发现table文件改变了,导致工程无法启动-解决
    1.背景工程使用了百度的离线ocr,需要导入资源,在提交仓库后拉代码,发现资源文件table改变了,很是奇怪最后发现是git在win的自动转换格式问题导致2.原因不同操作系统使用......
  • 百度地图区域绘制面
    <template><divclass="mapContainer"><!--<divid="tMap"/>--><divid="tMap"ref="tMap"/></div></template><script>import{TDIMap,BaiduM......
  • 百度地图手绘标点
    <template><divclass="mapContainer"><!--<divid="tMap"/>--><divid="tMap"ref="tMap"/></div></template><script>import{TDIMap,BaiduM......