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

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

1. 相关下载最新的库文件。将so文件的压缩文件解压出来,把相应架构下的so文件放入开发人员自己APP的相应架构下的目录中,建议所有放入。 程序兼容性会大大提升,将locSDK_5.X.jar文件复制到project的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; } }




原文地址:https://www.cnblogs.com/blfshiye/p/5387715.html