package com.jiuqi.njt.service;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.ExecutionException;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.search.core.LatLonPoint;
import com.jiuqi.njt.data.CheckStateInterface;
import com.jiuqi.njt.data.OptsharepreInterface;
import com.jiuqi.njt.model.NameIDMap;
import com.jiuqi.njt.ui.WearthActivityNew;
import com.jiuqi.njt.ui.weather.GetWeatherNewTaskNew;
import com.jiuqi.njt.ui.weather.WeatherBean;
import com.jiuqi.njt.util.AMapUtil;
import com.jiuqi.njt.util.Constants;
import com.jiuqi.njt.util.UIUtil;
import com.jqyd.android.module.lbs.LocationClient;
import com.jqyd.android.module.lbs.Interface.ILocationListener;
import com.jqyd.android.module.lbs.bean.LocationInfo;
import com.jqyd.android.module.lbs.util.JqydDateUtil;
/**
* 天气预报推送服务(暂定一天两次)
*
* @author malingya
*
*/
public class WeatherService extends Service implements AMapLocationListener {
private final static String TAG = "WEATHER_SERVICE";
private AlarmManager upAlarm;
private StringBuffer sBuffer;
// private LocationManagerProxy mAMapLocManager;//采用百度定位,高德定位方法遗弃
private String cityId;
private boolean flag = false;
private PendingIntent upPi;
private String province;
private String city;
private int startHour = 7; // 开始时间的小时
private int startMinute = 00; // 开始时间的分钟
private int endHour = 19; // 结束时间的小时
private int endMinute = 00; // 结束时间的分钟
private TimeZone china = TimeZone.getTimeZone("GMT+08:00");
// private WriteFile writeFile = new WriteFile(TAG
// + JqydDateUtil.getDateDayOne(new Date()));
private SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy年-MM月dd日-HH时mm分ss秒");
private OptsharepreInterface sharePre;
@Override
public void onCreate() {
super.onCreate();
Log.i("service", "-----WeatherService oncreate----");
// writeFile.writeToFileAdditional("-----WeatherService oncreate----");
upAlarm = (AlarmManager) this.getSystemService(ALARM_SERVICE);
sharePre = new OptsharepreInterface(WeatherService.this);
}
@Override
public void onStart(Intent intent, int startId) {
Log.i("service", "-----WeatherService onStart----");
super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("service", "-----WeatherService onStartCommand----");
setRunTime();
TimeData timeData = getTimeData(startHour, startMinute, endHour,
endMinute);
// writeFile.writeToFileAdditional(sharePre.getPres("sendTime")
// + "--"
// + JqydDateUtil.getDateDayTwo(new Date())
// + "=="
// + "sharePre.getPres"
// + (sharePre.getPres("sendTime").equals(JqydDateUtil
// .getDateDayTwo(new Date()))) + "--"
// + timeData.getTimeState() + "--"
// + formatter.format(new Date(timeData.getJgsj())));
// writeFile.writeToFileAdditional("下次执行时间 状态="
// + formatter.format(timeData.getJgsj()));
upAlarm.set(AlarmManager.RTC_WAKEUP, timeData.getJgsj(), upPi);
// enableMyLocation();
/**
* 当今天没有推送过天气或者是在设置的推送时间点上时就执行定位
*/
if (!sharePre.getPres("sendTime").equals(
JqydDateUtil.getDateDayTwo(new Date()))
|| timeData.getTimeState() > 2) {
enableMyLocation();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("service", "-----WeatherService onDestroy----");
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
Log.i("service", "-----WeatherService onUnbind----");
return super.onUnbind(intent);
}
/**
* 设置参数
*/
private void setRunTime() {
Intent upIntent = new Intent(WeatherService.this, WeatherService.class);
upPi = PendingIntent.getService(WeatherService.this, 0, upIntent, 0);
}
/**
*
* @author joe
*
*/
private class TimeData {
/**
* 上报状态 0:当前时间小于开始时间就就休眠到今天的开始时间. 1:当前时间大于开始时间并小于结束时间就就休眠到今天的结束时间.
* 2:当前时间大于结束时间就休眠到明天的开始时间. 3:当前时间等于开始时间就需要上报一次,并休眠到今天的结束时间.
* 4:当前时间等于结束时间就需要上报一次,并休眠到明天的开始时间.
*/
private int timeState;
/**
* 间隔时间(单位分钟)
*/
private long jgsj;
public int getTimeState() {
return timeState;
}
public void setTimeState(int timeState) {
this.timeState = timeState;
}
public long getJgsj() {
return jgsj;
}
public void setJgsj(long jgsj) {
this.jgsj = jgsj;
}
}
/**
* 获取上报时间
*
* @param startHour
* 开始时间的小时
* @param startMinute
* 开始时间的分钟
* @param endHour
* 结束时间的小时
* @param endMinute
* 结束时间的分钟
* @return
*/
private TimeData getTimeData(int startHour, int startMinute, int endHour,
int endMinute) {
/**
* 获取开始时间和结束时间(单位是分钟)
*/
int startMinuteTime = startHour * 60 + startMinute;
int endMinuteTime = endHour * 60 + endMinute;
TimeData timeData = new TimeData();
Calendar calendar = Calendar.getInstance(china);
long jgsj = 0;
/**
* 获取当前的时间(单位是分钟)
*/
int nowMinuteTime = calendar.get(Calendar.HOUR_OF_DAY) * 60
+ calendar.get(Calendar.MINUTE);
/**
* 如果当前时间小于开始时间就就休眠到今天的开始时间
*/
if (nowMinuteTime < startMinuteTime) {
timeData.setTimeState(0);
jgsj = JqydDateUtil.getTodayHourMinCalendar(startHour, startMinute)
.getTimeInMillis();
}
/**
* 如果当前时间大于开始时间并小于结束时间就就休眠到今天的结束时间
*/
else if (nowMinuteTime > startMinuteTime
&& nowMinuteTime < endMinuteTime) {
timeData.setTimeState(1);
jgsj = JqydDateUtil.getTodayHourMinCalendar(endHour, endMinute)
.getTimeInMillis();
}
/**
* 如果当前时间大于结束时间就休眠到明天的开始时间
*/
else if (nowMinuteTime > endMinuteTime) {
timeData.setTimeState(2);
jgsj = JqydDateUtil.getTomorrowHourMinCalendar(startHour,
startMinute).getTimeInMillis();
}
/**
* 如果当前时间等于开始时间就需要上报一次,并休眠到今天的结束时间
*/
else if (nowMinuteTime == startMinuteTime) {
timeData.setTimeState(3);
jgsj = JqydDateUtil.getTodayHourMinCalendar(endHour, endMinute)
.getTimeInMillis();
}
/**
* 如果当前时间等于结束时间就需要上报一次,并休眠到明天的开始时间
*/
else if (nowMinuteTime == endMinuteTime) {
timeData.setTimeState(4);
jgsj = JqydDateUtil.getTomorrowHourMinCalendar(startHour,
startMinute).getTimeInMillis();
}
timeData.setJgsj(jgsj);
return timeData;
}
/**
* 推送天气信息
*/
private void sendWeather(WeatherBean weather) {
// 今天天气温度
String dqwdstr = weather.getOneCelsius();
// 今天天气描述
String dqtqstr = weather.getOneCloud();
// 风速
String fsstr = weather.getOneWind();
sBuffer = new StringBuffer();
sBuffer.append("");
sBuffer.append(dqwdstr);
sBuffer.append("\r");
sBuffer.append(dqtqstr);
sBuffer.append("\r");
sBuffer.append(fsstr);
sBuffer.append("\r");
Intent intent = new Intent(WeatherService.this, WearthActivityNew.class);
intent.putExtra("flag", true);
intent.putExtra("WeatherBean", weather);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
Log.i("service", "-----WeatherService 发送天气预报信息---");
UIUtil.sendNotification(WeatherService.this, "天气预报",
sBuffer.toString(), intent);
flag = true;
/**
* 记录推送时间
*/
sharePre.putPres("sendTime", JqydDateUtil.getDateDayTwo(new Date()));
}
/**
* 开始定位
*/
public void enableMyLocation() {
// if (mAMapLocManager == null) {
// mAMapLocManager = LocationManagerProxy
// .getInstance(WeatherService.this);
// }
// 判断是否有网络,没有不请求,不上报
// Location API定位采用GPS和网络混合定位方式,时间最短是5000毫秒
CheckStateInterface checkStateInterface = new CheckStateInterface(
WeatherService.this);
if (checkStateInterface.checkConnection()) {
// mAMapLocManager.requestLocationUpdates(
// LocationProviderProxy.AMapNetwork, 5000, 1,
// WeatherService.this);
setUpBaiduLocation();
}
}
private void setUpBaiduLocation() {
/**
* 接收百度定位类传来的参数
*/
LocationClient client = new LocationClient(this);
client.request(new ILocationListener() {
@Override
public void onReceiveLocInfo(int locType, LocationInfo loc) {
Message msg = new Message();
if (loc != null) {
Log.i("service", "-----WeatherService 定位获取到位置onLocationChanged---");
Double geoLat = loc.getLat();
Double geoLng = loc.getLon();
StringBuffer sb = new StringBuffer();
if (loc.getSuccess() == 1) {
sb.append("定位方式:").append(loc.getPosour());
sb.append("\n定位时间:").append(
AMapUtil.convertToTime(loc.getTime()));
sb.append("\n位置描述:").append(loc.getContent());
sb.append("\n省:").append(loc.getProvince());
sb.append("\n市:").append(loc.getCity());
sb.append("\n区(县):").append(loc.getCountry());
msg.getData().putDouble("latitude", geoLat);
msg.getData().putDouble("longitude", geoLng);
msg.getData().putLong("time", loc.getTime());
msg.getData().putString("city", loc.getCity());
msg.getData().putString("country", loc.getCountry());
msg.getData().putString("province", loc.getProvince());
msg.getData().putInt("provider", loc.getPosour());
/**
* 更新客户端定位的手机位置信息
*/
sharePre.putPres(Constants.PREFERENCE_KEY_LATITUDE, geoLat+"");
sharePre.putPres(Constants.PREFERENCE_KEY_LONGITUDE,geoLng+"");
} else {
sb.append("定位失败,默认位置为郑州,请自行调整");
}
msg.obj = sb.toString();
msg.what = 1;
if (handler != null) {
handler.sendMessage(msg);
}
} else {
System.out.println("位置是空的");
}
}
});
}
private String getCityIdByName(String cityName) {
NameIDMap nameIDMap = new NameIDMap();
Map<String, String> mapAllNameID = nameIDMap.getMapAllNameID();
cityId = mapAllNameID.get(cityName);
return cityId;
}
// /**
// * 结束定位
// */
// public void disableMyLocation() {
// if (mAMapLocManager != null) {
// mAMapLocManager.removeUpdates(this);
// mAMapLocManager.destory();
// }
// mAMapLocManager = null;
// }
@Override
public void onLocationChanged(Location location) {
Log.e(TAG, "高德定位 "+location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "高德定位 "+provider);
}
@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "高德定位 "+provider);
}
@Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "高德定位 "+provider);
}
/**
* 获取位置
*/
@Override
public void onLocationChanged(final AMapLocation location) {
Message msg = new Message();
if (location != null) {
Log.i("service", "-----WeatherService 定位获取到位置onLocationChanged---");
Double geoLat = location.getLatitude();
Double geoLng = location.getLongitude();
String cityCode = "";
String desc = "";
StringBuffer sb = new StringBuffer();
Bundle locBundle = location.getExtras();
if (locBundle != null) {
cityCode = locBundle.getString("citycode");
desc = locBundle.getString("desc");
sb.append("定位方式:").append(location.getProvider());
// sb.append("\n定位成功:(").append(geoLng).append(",").append(geoLat).append(")");
sb.append("\n精 度 :").append(location.getAccuracy())
.append("米");
sb.append("\n定位时间:").append(
AMapUtil.convertToTime(location.getTime()));
sb.append("\n城市编码:").append(cityCode);
sb.append("\n位置描述:").append(desc);
sb.append("\n省:").append(location.getProvince());
sb.append("\n市:").append(location.getCity());
sb.append("\n区(县):").append(location.getDistrict());
sb.append("\n城市编码:").append(location.getCityCode());
sb.append("\n区域编码:").append(location.getAdCode());
msg.getData().putDouble("latitude", geoLat);
msg.getData().putDouble("longitude", geoLng);
msg.getData().putString("desc", desc);
msg.getData().putLong("time", location.getTime());
msg.getData().putDouble("radius", location.getAccuracy());
msg.getData().putString("city", location.getCity());
msg.getData().putString("country", location.getDistrict());
msg.getData().putString("province", location.getProvince());
msg.getData().putString("provider", location.getProvider());
/**
* 更新客户端定位的手机位置信息
*/
sharePre.putPres(Constants.PREFERENCE_KEY_LATITUDE, geoLat+"");
sharePre.putPres(Constants.PREFERENCE_KEY_LONGITUDE,geoLng+"");
} else {
sb.append("定位失败,默认位置为郑州,请自行调整");
}
msg.obj = sb.toString();
msg.what = 1;
if (handler != null) {
handler.sendMessage(msg);
}
} else {
System.out.println("位置是空的");
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
// 结束定位
// disableMyLocation();
province = msg.getData().getString("province");
city = msg.getData().getString("city");
String country = msg.getData().getString("country");
if (province == null) { // 如北京,省返回空
province = city;
}
if (!TextUtils.isEmpty(city)) {
// disableMyLocation();
if (city.contains("市")) {
getCityIdByName(city.substring(0, city.length() - 1));
}
Log.i("service", "-----WeatherService 通过位置获取天气信息---");
Double lat = msg.getData().getDouble("latitude");
Double lon = msg.getData().getDouble("longitude");
// String locinfo = String.valueOf(lon) + "," +
// String.valueOf(lat);
if (lat != 0.0 && lon != 0.0) {
WeatherBean weather = null;
try {
weather = new GetWeatherNewTaskNew(province, city,
WeatherService.this, false).execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* 获取到数据就推送
*/
if (null != weather
&& !"暂无数据".equals(weather.getOneCelsius())) {
weather.setProCity(province);
weather.setCity(city);
sendWeather(weather);
}
}
}
break;
default:
break;
}
}
};
}