package com.tx.weatherwidget;
/**
* 调用高德地图的天气api获取天气
*
*/
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.amap.api.location.AMapLocalWeatherForecast;
import com.amap.api.location.AMapLocalWeatherListener;
import com.amap.api.location.AMapLocalWeatherLive;
import com.amap.api.location.LocationManagerProxy;
import com.tx.weatherwidget.R;
public class WeatherService extends Service implements
AMapLocalWeatherListener{
private LocationManagerProxy mLocationManagerProxy;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
init();
}
/**
* 注册天气监听
*/
private void init() {
mLocationManagerProxy = LocationManagerProxy.getInstance(this);
mLocationManagerProxy.requestWeatherUpdates(
LocationManagerProxy.WEATHER_TYPE_LIVE, this);
}
@Override
public void onWeatherForecaseSearched(AMapLocalWeatherForecast arg0) {
// TODO Auto-generated method stub
}
@Override
public void onWeatherLiveSearched(AMapLocalWeatherLive aMapLocalWeatherLive) {
// TODO Auto-generated method stub
if(aMapLocalWeatherLive!=null && aMapLocalWeatherLive.getAMapException().getErrorCode() == 0){
String city = aMapLocalWeatherLive.getCity();//城市
String weather = aMapLocalWeatherLive.getWeather();//天气情况
String windDir = aMapLocalWeatherLive.getWindDir();//风向
String windPower = aMapLocalWeatherLive.getWindPower();//风力
String humidity = aMapLocalWeatherLive.getHumidity();//空气湿度
String reportTime = aMapLocalWeatherLive.getReportTime();//数据发布时间
updateView("城市: "+city+'\n'+
"风向: "+windDir+'\n'+
"风力: "+windPower+'\n'+
"天气情况: "+weather+'\n'+
"空气湿度: "+humidity+'\n'+
"数据发布时间: "+reportTime+'\n');
}else{
// 获取天气预报失败
Toast.makeText(this,"获取天气预报失败:"+ aMapLocalWeatherLive.getAMapException().getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
private void updateView(String info){
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.widget);
remoteViews.setTextViewText(R.id.weather, info);
AppWidgetManager manager = AppWidgetManager.
getInstance(getApplicationContext());
ComponentName provider = new ComponentName(
getApplicationContext(), WeatherProvider.class);
manager.updateAppWidget(provider, remoteViews);
}
}