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

1.申請百度AK

申請地址:http://lbsyun.baidu.com/apiconsole/key

在應用中的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]);
	}

}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章