1. 程式人生 > >android 百度API定位以及獲取天氣

android 百度API定位以及獲取天氣

1.申請百度AK

在應用中的manifest申明

<meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="dP15rUSoUIwDll5qYj71pNOn" />


2.註冊服務以及匯入jar包和so檔案

在lib/資料夾下匯入BaiduLBS_Android.jar

在lib/armeabi資料夾下匯入liblocSDK4d.so

註冊百度服務:

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

申明許可權:
<!-- 這個許可權用於進行網路定位 -->
    <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>

3.定位
package com.location.model;

import android.content.Context;
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.physical.training.utils.Utils;

public class LocationApi {

	private Context mContext;

	private static volatile LocationApi sApi;

	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();

	private double mPreLongitude = Integer.MIN_VALUE;
	private double mPreLatitude = Integer.MIN_VALUE;

	private OnLocationListener mLocationListener;

	private double mDistance = 0;

	private LocationApi(Context context) {
		mContext = context;
	}

	public static LocationApi getInstance(Context context) {
		if (sApi == null) {
			synchronized (LocationApi.class) {
				if (sApi == null) {
					sApi = new LocationApi(context.getApplicationContext());
				}
			}
		}
		return sApi;
	}

	public void setOnLocationListener(OnLocationListener l) {
		mLocationListener = l;
	}

	public void startLocation() {
		mLocationClient = new LocationClient(mContext); // 宣告LocationClient類
		mLocationClient.registerLocationListener(myListener); // 註冊監聽函式
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 設定定位模式
		option.setCoorType("bd09ll");// 返回的定位結果是百度經緯度,預設值gcj02
		option.setScanSpan(3000);// 設定發起定位請求的間隔時間
		option.setIsNeedAddress(true);// 返回的定位結果包含地址資訊
		option.setNeedDeviceDirect(true);// 返回的定位結果包含手機機頭的方向
		option.setOpenGps(true);
		mLocationClient.setLocOption(option);
		mLocationClient.start();//開始定位
		mLocationClient.requestLocation();

		mPreLongitude = Integer.MIN_VALUE;
		mPreLatitude = Integer.MIN_VALUE;
		mDistance = 0;

	}

	public void stopLocation() {
		if(mLocationClient != null) {
			mLocationClient.stop();
			mLocationClient.unRegisterLocationListener(myListener);
			mLocationClient = null;
			mPreLongitude = Integer.MIN_VALUE;
			mPreLatitude = Integer.MIN_VALUE;
			mDistance = 0;
		}
	}

	public class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			double longitude = location.getLongitude();
			double latitude = location.getLatitude();
			Log.e("LocationApi", longitude + "  " + latitude);
			Log.e("LocationApi", "mDistance++  = " + mDistance);
			if (mPreLongitude != Integer.MIN_VALUE) {
				mDistance += Math.abs(Utils.getDistance(mPreLongitude, mPreLatitude, longitude, latitude)) + 100;
			}
			Log.e("LocationApi", "mDistance--  = " + mDistance);

			if (mLocationListener != null) {
				mLocationListener.onLocationChange();
			}
			mPreLongitude = longitude;
			mPreLatitude = latitude;
		}
	}

	public int getDistance() {
		return (int) mDistance;
	}

	public interface OnLocationListener {
		public void onLocationChange();
	}

}

4.天氣

WeatherApi.java定位到經緯度

package com.weather.model;

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.common.data.HttpEventHandler;
import com.physical.training.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.util.Log;

public class WeatherApi {

	private Context mContext;

	private static volatile WeatherApi sApi;

	private WeatherFactory mWeatherFactory;

	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();

	OnWeatherUpdateListener mListener;

	WeatherInfo mInfo;

	private WeatherApi(Context context) {
		mContext = context;

		mLocationClient = new LocationClient(mContext); // 宣告LocationClient類
		mLocationClient.registerLocationListener(myListener); // 註冊監聽函式

		mWeatherFactory = new WeatherFactory();
		mWeatherFactory.setHttpEventHandler(mEventHandler);
	}

	public void setOnWeatherUpdateListener(OnWeatherUpdateListener l) {
		mListener = l;
	}

	public void startLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 設定定位模式
		option.setCoorType("bd09ll");// 返回的定位結果是百度經緯度,預設值gcj02
		option.setScanSpan(60 * 60 * 1000);// 設定發起定位請求的間隔時間
		option.setIsNeedAddress(true);// 返回的定位結果包含地址資訊
		option.setNeedDeviceDirect(true);// 返回的定位結果包含手機機頭的方向
		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}

	public void stopLocation() {
		mLocationClient.stop();
	}

	public static WeatherApi getInstance(Context context) {
		if (sApi == null) {
			synchronized (WeatherApi.class) {
				if (sApi == null) {
					sApi = new WeatherApi(context.getApplicationContext());
				}
			}
		}
		return sApi;
	}

	public class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			Log.d("LocSDK5", location.getCity() + "  " + location.getCityCode());
			mWeatherFactory.downloaDatas(location.getLongitude() + "," + location.getLatitude());
		}
	}

	public WeatherInfo getWeatherInfo() {
		return mInfo;
	}

	public void destory() {
		mLocationClient.unRegisterLocationListener(myListener);
	}

	private HttpEventHandler<WeatherInfo> mEventHandler = new HttpEventHandler<WeatherInfo>() {

		@Override
		public void HttpSucessHandler(WeatherInfo arg0) {
			mInfo = arg0;
			if (mListener != null) {
				mListener.onWeatherUpdate();
			}
			if (mInfo != null) {
				NotificationManager notificationManager = (NotificationManager) mContext
						.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
				Notification notification = new Notification(R.drawable.ic_launcher, "weather",
						System.currentTimeMillis());
				notification.setLatestEventInfo(mContext,
						mContext.getResources().getString(R.string.notification_weather_title, mInfo.cityName),
						mInfo.weather + "," + mInfo.temperature + "," + mInfo.wind, null);
				notificationManager.notify(Integer.MAX_VALUE, notification);
			}
		}

		@Override
		public void HttpFailHandler() {

		}
	};

	public interface OnWeatherUpdateListener {
		public void onWeatherUpdate();
	}

}

WeatherFactory.java建立訪問天氣的uri,獲取天氣的json資料,http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=T2AHbrsEn5FaSg4Iir8YfP1U,location表示經緯度,用分號隔開
package com.weather.model;

import java.io.IOException;

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

import android.util.Log;

import com.common.data.HttpJsonFactoryBase;

public class WeatherFactory extends HttpJsonFactoryBase<WeatherInfo> {

	@Override
	protected WeatherInfo analysisData(JSONObject json) throws IOException {
		WeatherInfo info = new WeatherInfo();
		Log.e("WeatherFactory", json.toString());
		try {
			JSONArray results = json.getJSONArray("results");
			JSONObject result = results.getJSONObject(0);
			info.cityName = result.getString("currentCity");
			info.pm25 = result.getString("pm25");
			JSONArray weatherDatas = result.getJSONArray("weather_data");
			JSONObject weatherData = weatherDatas.getJSONObject(0);
			info.weather = weatherData.getString("weather");
			info.wind = weatherData.getString("wind");
			info.temperature = weatherData.getString("temperature");
			Log.e("WeatherFactory", info.toString());
			return info;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected String createUri(Object... arg0) {
		return String.format(
				"http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=T2AHbrsEn5FaSg4Iir8YfP1U",
				arg0[0]);
	}

}