package com.jqyd.shareInterface;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.jqyd.app.LocationUtils;
import com.jqyd.app.MyApp;
import com.jqyd.app.ShareMethod;
import com.jqyd.model.LocationModule;
import com.jqyd.model.RecordModel;
import com.jqyd.son.Scjc;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class JqgjService extends Service {
private static String TAG = "LXSB";
private MyApp myApp = null;// 共享池对象
private WakeLock wakeLock = null;
public Optdb_interfce db = null;
private Optsharepre_interface shareFile = null;
private CheckState_interface checkState = null;
private ShareMethod shareMethd = null;
private TelephonyManager tm = null;
private UpdataToServer server = null;
private String currDay = "";
private String imsi = "";
private String ontime;// 上班时间
private String offtime;// 下班时间
private String intervaltime = "0";// 间隔时间
private String execute;// 是否执行任务
private String hasResult = "N";// 与服务器交互结果
private boolean hasTask = false;// 是否有任务
private boolean task = true;
private int startTime = 0;
private int endTime = 0;
long beforeTimeTemp = 0;
long currTime = 0;
String serverTime = "";
String log = "";
boolean isSuccess = false;// 当天是否与服务器交互过
boolean isOnReload = false;// 是否重启service
private TimeListenerThread timeThread = null;
private Baidu_location baidu = null;
@Override
public void onCreate() {
// TODO Auto-generated method stub
recordLog("%%%%%%%%%%%%%%%启动onCreate%%%%%%%%%%%%%%%");
// 设置优先级为最高
//setForeground(true);
// 保持手机在待机的状态下service依然能够正常运行
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
JqgjService.class.getName());
wakeLock.acquire();
myApp = (MyApp) this.getApplication();
isOnReload = true;
// 启动主线程
timeThread = new TimeListenerThread();
timeThread.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isOnReload) {// 记录日志
isOnReload = false;
recordLog("%%%%%%%%%%%%%%%启动onStartCommand%%%%%%%%%%%%%%%");
}
// 当前线程已经启动
if (timeThread == null || !timeThread.isAlive()
|| timeThread.isInterrupted()) {
// 启动主线程
timeThread = new TimeListenerThread();
timeThread.start();
} else {
recordLog("---------当前线程运行正常-------------");
}
// 此值定义,一旦service被杀死会自动重启,可能暂时还不起作用(待查)
return START_STICKY;
}
/**
* 时间监听线程
*
* @author Administrator
* 在当天连续上报结束或没有连续上报计划的时候,将currTime设置为第二天的开始时间,
* 修正原来无限增加的情况,同时在countSleepTime方法中做一个预防如果计算的sleeptime为0则设置sleeptime为一个小时
*/
class TimeListenerThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
Looper.prepare();
recordLog("*-*启动时间监听线程TimeListenerThread*-*");
shareFile = new Optsharepre_interface(JqgjService.this);
try {
log = "延时1分钟,防止手机死机";
Log.i(TAG, log);
recordLog(log);
Thread.sleep(60000);// 开机延时1分钟,防止手机死机
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
recordLog(e1.getMessage());
}
// 获取服务器端最新的时间节点
getServerTime();
while (task) {
// 判断当天是否与服务器交互过,每天交互一次
SimpleDateFormat formDate = new SimpleDateFormat("yyyyMMdd");
String hisDay = shareFile.getDataFromPres("hisDay");
if (!currDay.equals(hisDay)) {// 当天没有与服务器交互过
handServer();
if (isSuccess) {// 与服务器交互成功,更新终端保存的日期参数
shareFile.editPres("hisDay", currDay);
}
}
// 从终端读取任务参数
searchTask();
// 终端配置文件中有任务,且当天允许上报
recordLog("终端是否保存有数据:hasResult=" + hasResult
+ ",判断是否有任务:hasTask=" + hasTask);
if (hasResult.equals("Y") && hasTask) {
if (currTime >= startTime && currTime <= endTime) {
// 判断当天是否已经上报过位置了,如果上报过了,则从上次上报的位置开始上报,否则,立刻上报。
String hisSbTime = shareFile
.getDataFromPres("hisSbTime");
recordLog("^^^^^^^^^^^^^^^上次上报时间^^^^^^^^^^^^^^^:"
+ hisSbTime);
if (hisSbTime.equals("")) {// 当天首次上报
beforeTimeTemp = currTime;
// 更新配置文件中历史上报时间点
shareFile.editPres("hisSbTime",
String.valueOf(currTime));
// 启动位置上报线程
new WzsbThread().start();
hisSbTime = shareFile.getDataFromPres("hisSbTime");
// 启动位置上报线程后在配置文件中记录当前上报时间点
/**
* 计算休眠时间 休眠时间 = 间隔时间-((当前时间点-上班时间)%间隔时间)
*/
int jgsj = Integer.valueOf(intervaltime).intValue();
long beforeTime = (beforeTimeTemp - startTime)
% jgsj;
long sleepTime = countSleepTime(beforeTime, jgsj);// 毫秒
// 更新下个时间判断点
currTime = beforeTimeTemp + (sleepTime / 1000 / 60);
log = "*****************位置上报完成后,定义下次上报时间点:"
+ currTime + "*****************";
Log.i(TAG, log);
recordLog(log);
recordLog("休眠后当时间为:" + currTime + ",在:" + currTime
/ 60 + "点" + currTime % 60 + "分发送");
try {
Log.i(TAG, "计算当天首个上报点距离下个最近的上报点的时间差");
recordLog("计算当天首个上报点距离下个最近的上报点的时间差,休眠--休眠时间:"
+ String.valueOf(sleepTime));
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
}
} else {// 当天已经上报过位置了
beforeTimeTemp = currTime;
hisSbTime = shareFile.getDataFromPres("hisSbTime");
long jgsj = Long.valueOf(intervaltime).longValue();
/**
* 判断当前时间点是否需要上报 (当前时间点-上次上报时间)/间隔时间==0 如果为零则无需上报
*/
long isUp = (beforeTimeTemp - Long.valueOf(
hisSbTime).longValue())
/ jgsj;
if (isUp != 0) {// 上报
// 启动位置上报线程
new WzsbThread().start();
/**
* 记录上次上报时间
* 上次上报时间=上次上报时间点+((当前时间点-上次上报时间)/间隔时间)*间隔时间
*/
// 更新配置文件中历史上报时间点
long hisTime = Long.valueOf(hisSbTime)
.longValue()
+ ((beforeTimeTemp - Long.valueOf(
hisSbTime).longValue()) / jgsj)
* jgsj;
shareFile.editPres("hisSbTime",
String.valueOf(hisTime));
}
/**
* 计算休眠时间 休眠时间 = 间隔时间-((当前时间点-上次上报时间)%间隔时间)
*/
// hisSbTime =
// shareFile.getDataFromPres("hisSbTime");--原程序此处有误,不应该从配置文件中取更新后的参数,而应该是第一次读取的参数
// long beforeTime = (beforeTimeTemp - Long.valueOf(
// hisSbTime).longValue())% jgsj;
long beforeTime = (beforeTimeTemp - Long.valueOf(
hisSbTime).longValue())
% jgsj;
long sleepTime = countSleepTime(beforeTime, jgsj);
currTime = beforeTimeTemp + sleepTime / 1000 / 60;
log = "*****************位置上报完成后,定义下次上报时间点:"
+ currTime + "*****************";
Log.i(TAG, log);
recordLog(log);
recordLog("休眠后当时间为:" + currTime + ",在:" + currTime
/ 60 + "点" + currTime % 60 + "分发送");
try {
log = "当天上报过位置点,关机再开机、服务重新启动、正常间隔上报,休眠--休眠时间:"
+ String.valueOf(sleepTime);
Log.i(TAG, log);
recordLog(log);
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
}
// 更新下个时间判断点
}
} else {
// 清空历史上报时间点
shareFile.editPres("hisSbTime", "");
isSuccess = false;
// 判断当前时间点是在上班时间前,还是上班时间后
if (currTime < startTime) {
/**
* 休眠,到点后开始上报 休眠时间=上班时间减去当前时间节点
*/
long sleepTime = countSleepTime(currTime, startTime);
currTime = currTime + sleepTime / 1000 / 60;
recordLog("休眠后当时间为:" + currTime + ",在:" + currTime
/ 60 + "点" + currTime % 60 + "分发送");
try {
log = "当前时间点在上班时间前,故休眠至上班时间,休眠时间:" + sleepTime;
Log.i(TAG, log);
recordLog(log);
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
}
} else {
/**
* 下班了,休眠 休眠时间=第二天的上班时间减去下班时间
*/
recordLog("休眠前时间为:currTime=" + currTime
+ ",startTime=" + startTime);
long beforeTime = currTime;
long afterTime = 24 * 60 + startTime;
long sleepTime = countSleepTime(beforeTime,
afterTime);
currTime = new Long(startTime).longValue();
// currTime = currTime + sleepTime / 1000 / 60;
recordLog("休眠后时间为:" + currTime + ",在第二天的:"
+ ((currTime / 60) ) + "点" + currTime
% 60 + "分发送");
try {
log = "当前时间点在下班时间后,故休眠至第二天上班时间,休眠时间:"
+ sleepTime;
Log.i(TAG, log);
recordLog(log);
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
}
}
}
} else {
/**
* 当天没有上报任务或未指定连续上报计划,休眠 休眠时间=第二天上班时间减去当前时间差
*/
// 清空历史上报时间点
recordLog("休眠前时间为:currTime=" + currTime + ",startTime="
+ startTime);
shareFile.editPres("hisSbTime", "");
isSuccess = false;
long beforeTime = currTime;
long afterTime = 24 * 60 + startTime;
long sleepTime = countSleepTime(beforeTime, afterTime);
currTime = new Long(startTime).longValue();
// currTime = currTime + sleepTime / 1000 / 60;
recordLog("休眠后时间为:" + currTime + ",在第二天的:"
+ ((currTime / 60) ) + "点" + currTime % 60
+ "分发送");
try {
if (!hasTask) {
log = "未指定连续上报计划,休眠--休眠时间:"
+ String.valueOf(sleepTime);
} else {
log = "当天没有上报任务,休眠--休眠时间:"
+ String.valueOf(sleepTime);
}
Log.i(TAG, log);
recordLog(log);
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
}
}
}
Looper.loop();
}
}
/**
* 获取服务器端最新的时间节点
*/
public void getServerTime() {
recordLog("请求网络时间开始");
String timeTemp = "";
long ld = 0;
// 获取网络时间
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
SimpleDateFormat sdfDay = new SimpleDateFormat("yyyyMMdd");
TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai"); // 设置时区
sdf.setTimeZone(timezone);
sdfDay.setTimeZone(timezone);
shareMethd=new ShareMethod(JqgjService.this);
ld=shareMethd.getServerTime();
if (ld != 0) {
Date date = new Date(ld);
timeTemp = sdf.format(date);
currDay = sdfDay.format(date);
serverTime = timeTemp;
log = "请求服务器获取时间参数成功:" + serverTime + " currDay " + currDay;
Log.i(TAG, log);
recordLog(log);
} else {
log = "请求服务器获取时间参数失败,采用手机端时间";
// 采用手机端时间
timeTemp = sdf.format(new Date());
currDay = sdfDay.format(new Date());
log += ",手机端时间:" + timeTemp + " currDay " + currDay;
Log.i(TAG, log);
recordLog(log);
}
upCurrTime(timeTemp);// 更新当前的全局时间变量upCurrTime
}
private void upCurrTime(String timeTemp) {
// 更新当前的全局时间变量
String[] serverTim = timeTemp.split(":");
int currHour = 0;
int currMin = 0;
try {
currHour = Integer.parseInt(serverTim[0]);
currMin = Integer.parseInt(serverTim[1]);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
recordLog("与服务器交互完毕后,解析时间出现异常");
}
currTime = currHour * 60 + currMin;
recordLog("更新当前时间为currTime " + currTime);
}
/**
* 时间判断并计算休眠时间
*/
public long countSleepTime(long beforTime, long afterTime) {
long sleepTime = (afterTime - beforTime) * 60 * 1000;// 毫秒
recordLog("计算休眠时间:" + beforTime + "," + afterTime + ",结果:" + sleepTime
+ "毫秒");
if(sleepTime ==0){
sleepTime = 60*60*1000;
recordLog("因为休眠时间为0所以设置休眠时间为1小时");
}
Log.i(TAG, log);
return sleepTime;
}
/**
* 查找任务并赋给全局变量
*
* 有数据的时候,直接调用的为从配置文件中查找的数据,而不是使用默认的上下班时间
*/
public void searchTask() {
recordLog("从终端配置文件中查找任务");
ontime = shareFile.getDataFromPres("SBSJ");
offtime = shareFile.getDataFromPres("XBSJ");
intervaltime = shareFile.getDataFromPres("JGSJ");
execute = shareFile.getDataFromPres("RWZL");
System.out.println(" ontime " + ontime + " offtime " + offtime
+ " intervaltime " + intervaltime + " execute " + execute);
if (ontime.equals("-1") || offtime.equals("-1")
|| intervaltime.equals("-1") || execute.equals("-1")
|| ontime.equals("-2") || offtime.equals("-2")
|| intervaltime.equals("-2") || execute.equals("-2")) {
hasResult = "N";// 无数据
hasTask = false;
} else {// 有数据
hasResult = "Y";
int onhour = 8;
int onminute = 30;
int offhour = 18;
int offminute = 0;
// 定义上班时间、下班时间参数值有效
try {
onhour = Integer.parseInt(ontime.split(":")[0]);
onminute = Integer.parseInt(ontime.split(":")[1]);
offhour = Integer.parseInt(offtime.split(":")[0]);
offminute = Integer.parseInt(offtime.split(":")[1]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
String[] kqcl = shareFile.getDataFromPres("KQCL")
.split("#");
ontime = kqcl[0];
offtime = kqcl[1];
onhour = Integer.parseInt(ontime.split(":")[0]);
onminute = Integer.parseInt(ontime.split(":")[1]);
offhour = Integer.parseInt(offtime.split(":")[0]);
offminute = Integer.parseInt(offtime.split(":")[1]);
} catch (Exception ex) {
ex.printStackTrace();
onhour = 8;
onminute = 30;
offhour = 18;
offminute = 0;
}
recordLog("读取登录时配置文件中的上班时间、下班时间出错!" + e.getMessage());
}
log = "终端配置文件中没有连续上报任务参数,读取久其管家登录时的上班时间、下班时间:" + ontime + ","
+ offtime;
Log.i(TAG, log);
recordLog(log);
startTime = onhour * 60 + onminute;
endTime = offhour * 60 + offminute;
if (execute.equals("1")) {
// 有任务
hasTask = true;
} else {
// 无任务
hasTask = false;
}
}
log = "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^从终端表中查找任务打印^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n"
+ "上班时间:"
+ ontime
+ ",下班时间:"
+ offtime
+ ",间隔时间:"
+ intervaltime
+ "\n"
+ "终端是否保存有数据:"
+ hasResult
+ ",判断是否有任务:"
+ hasTask;
Log.i(TAG, log);
recordLog(log);
}
/**
* 与服务器交互
*/
public void handServer() {
recordLog("与服务器交互,更新终端任务参数");
boolean circle = true;
String result = "-1";
int i = 1;
// 取出IMSI号
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imsi = tm.getSubscriberId(); // 取出现在的IMSI号码
JSONObject obj = new JSONObject();
while (circle) {
try {
obj.put("gguid", shareFile.getDataFromPres("GGUID"));
obj.put("guid", shareFile.getDataFromPres("GUID"));
obj.put("username", shareFile.getDataFromPres("REGSIM"));
obj.put("password", shareFile.getDataFromPres("PWD"));
obj.put("imsi", imsi);
obj.put("zdlx", myApp.getVersion());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
recordLog(e1.getMessage());
}
log = "上传至服务器的交互参数:" + obj.toString();
Log.i(TAG, log);
recordLog(log);
server = new UpdataToServer(JqgjService.this);
result = server.dataToServer("JCLXSB", obj);
log = "请求服务器发送连接请求次数,与服务器交互结果:" + i + "," + result;
Log.i(TAG, log);
recordLog(log);
if (result.equals("-1") || result.equals("500")) {
recordLog("第" + i + "次与服务器交互失败");
if (i == 3) {
circle = false;
} else {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
}
i++;
}
} else {
circle = false;
}
}
Log.i(TAG, "与服务器交互更新结果:" + result);
recordLog("与服务器交互更新结果:" + result);
String timeTemp = "";
if (!result.equals("-1") && !result.equals("500")) {// 交互成功
try {
JSONObject taskobj = new JSONObject(result);
String res = taskobj.getString("result");
serverTime = taskobj.getString("time");
log = "与服务器交互成功,交互时间:" + serverTime;
recordLog(log);
int param = Integer.valueOf(res).intValue();
switch (param) {
case 0:// 更新任务参数
JSONObject taskObj = taskobj.getJSONObject("tasks");
shareFile = new Optsharepre_interface(JqgjService.this);
shareFile.editPres("SBSJ", taskObj.getString("ontime"));
shareFile.editPres("XBSJ", taskObj.getString("offtime"));
shareFile.editPres("JGSJ",
taskObj.getString("intervaltime"));
shareFile.editPres("RWZL", taskObj.getString("execute"));
log = "与服务器交互成功,更新终端保存的任务参数";
recordLog(log);
break;
case -999:
shareFile.editPres("SBSJ", "-2");
shareFile.editPres("XBSJ", "-2");
shareFile.editPres("JGSJ", "-2");
shareFile.editPres("RWZL", "-2");
log = "鉴权失败,删除终端保存的任务参数";
recordLog(log);
break;
case 1:// 删除终端数据
shareFile.editPres("SBSJ", "-2");
shareFile.editPres("XBSJ", "-2");
shareFile.editPres("JGSJ", "-2");
shareFile.editPres("RWZL", "-2");
log = "执行删除终端保存的任务参数指令";
recordLog(log);
break;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
}
isSuccess = true;
timeTemp = serverTime;
} else {// 更新失败,取前一天上报指令
log = "由于网络或服务器问题造成与后台交互失败,此时取昨天的任务指令执行";
// 采用手机端时间
SimpleDateFormat formdate = new SimpleDateFormat("HH:mm");
timeTemp = formdate.format(new Date());
log += ",手机端时间:" + timeTemp;
recordLog(log);
}
// 与服务器交互完毕后,更新当前的全局时间变量
upCurrTime(timeTemp);
}
/**
* 位置上报线程
*
* @author Administrator
*
*/
class WzsbThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
Looper.prepare();
log = "---**---启动位置上报线程---**---";
Log.i(TAG, log);
recordLog(log);
upLocation();
log = "---**---位置上报流程结束---**---";
Log.i(TAG, log);
recordLog(log);
Looper.loop();
}
}
/**
* 位置上报
*
* @author Administrator
*
*/
public void upLocation() {
recordLog("开始上报位置");
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
String[] startUpStr = dateFormat.format(new Date()).split(":");
int startUpTime = 0;
int currHour = 0;
int currMin = 0;
try {
currHour = Integer.parseInt(startUpStr[0]);
currMin = Integer.parseInt(startUpStr[1]);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
recordLog("开始上报位置记录时间点,解析时间出现异常");
}
startUpTime = currHour * 60 + currMin;
String userName = "";// 登录者姓名
String res = "-1";//
shareFile = new Optsharepre_interface(JqgjService.this);
JSONObject jsonObject = new JSONObject();
JSONArray jsonArr = new JSONArray();
shareMethd = new ShareMethod(JqgjService.this);
LocationModule loc = new LocationUtils(JqgjService.this).takeCellInfos();
db = new Optdb_interfce(JqgjService.this);
// 获得登录者姓名
userName = db.searchEmpName(shareFile.getDataFromPres("GUID"));
db.close_SqlDb();
JSONObject object =null;
Message message = new Message();
message.what = 2;
mainHandler.sendMessage(message);
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
LocationUtils locationUtils = new LocationUtils(JqgjService.this);
boolean b = locationUtils.getLocation(loc, "All", "", baidu);
if (b) {
// 位置获取成功
try {
object = new JSONObject();
object.put("cosim", shareFile.getDataFromPres("COSIM"));
object.put("regsim", shareFile.getDataFromPres("REGSIM"));
object.put("time", loc.getTime());
object.put("lon", loc.getLon());
object.put("lat", loc.getLat());
object.put("cell_id", loc.getCell_id());
object.put("lac_code", loc.getLac());
object.put("country_code", loc.getCcode());
object.put("ncode", loc.getNcode());
object.put("signal_strength", "0");
object.put("loc_method", loc.getDw_type());
object.put("radius", loc.getRadius());
object.put("gguid", shareFile.getDataFromPres("GGUID"));
object.put("guid", shareFile.getDataFromPres("GUID"));
object.put("zdmc", userName);
object.put("yys", loc.getYys());
object.put("jiange", intervaltime);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
recordLog(e1.getMessage());
//出现异常的话,说明数据有问题,置为空
object=null;
}
} else {
// 位置获取失败
int state = loc.getState();
if (state == -1) {
recordLog("gps设备处于关闭状态");
shareFile.editPres("errCode", "-999");
} else if (state == 0) {
// 卫星获取位置失败
shareFile.editPres("errCode", "-998");
}
}
freeBdListener();
if(object==null){
//说明没有数据
return;
}
jsonArr.put(object);// 放入JSONArray数组中
try {
jsonObject.put("recordList", jsonArr);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
recordLog(e1.getMessage());
}
log = "上传位置参数至服务器端--------" + jsonObject.toString();
recordLog(log);
server = new UpdataToServer(JqgjService.this);
String result = server.dataToServer("LXSB", jsonObject);
try {
db = new Optdb_interfce(JqgjService.this);
if (result != null && !result.equals("-1") && !result.equals("500")) {
JSONObject obj = new JSONObject(result);
JSONArray resultList = (JSONArray) obj.get("resultList");
for (int i = 0; i < resultList.length(); i++) {
JSONObject obj_info = (JSONObject) resultList.get(i);
res = obj_info.getString("result");
if (res.equals("0")) {// 上报成功
recordLog("上报位置成功");
} else {// 上报失败,保存当前这条数据,同时不删除之前上报的数据
Log.i(TAG, "上报失败写入终端数据库");
recordLog("上报位置失败,保存当条记录至终端数据库表");
ArrayList<Object> list = new ArrayList<Object>();
JSONObject jsonObj = jsonArr.getJSONObject(0);
RecordModel recordModel = new RecordModel();
if (jsonObj.getLong("time") == 0) {
recordModel.setAdd_time(String.valueOf(new Date()
.getTime()));
} else {
recordModel.setAdd_time(String.valueOf(jsonObj
.getLong("time")));
}
recordModel.setCcode(jsonObj.getString("country_code"));
recordModel.setCid(jsonObj.getString("cell_id"));
recordModel.setGid("999");
recordModel.setLac(jsonObj.getString("lac_code"));
recordModel.setLat(String.valueOf(jsonObj
.getDouble("lat")));
recordModel.setLon(String.valueOf(jsonObj
.getDouble("lon")));
recordModel.setNcode(jsonObj.getString("ncode"));
recordModel.setRaduis(jsonObj.getString("radius"));
recordModel.setWzbs(String.valueOf(jsonObj
.getInt("loc_method")));
recordModel.setXhqd(jsonObj
.getString("signal_strength"));
recordModel.setResult(jsonObj.getString("jiange"));// 存放间隔时间
recordModel.setBz(jsonObj.getString("yys"));// 备注字段存放运营商
list.add(recordModel);
db.updateToDb("T_RECORDS", list);
}
}
} else {// 上报失败,保存当前这条数据
Log.i(TAG, "上报失败写入终端数据库");
recordLog("上报位置失败,保存当条记录至终端数据库表");
ArrayList<Object> list = new ArrayList<Object>();
JSONObject jsonObj = jsonArr.getJSONObject(0);
RecordModel recordModel = new RecordModel();
if (jsonObj.getLong("time") == 0) {
recordModel
.setAdd_time(String.valueOf(new Date().getTime()));
} else {
recordModel.setAdd_time(String.valueOf(jsonObj
.getLong("time")));
}
recordModel.setCcode(jsonObj.getString("country_code"));
recordModel.setCid(jsonObj.getString("cell_id"));
recordModel.setGid("999");
recordModel.setLac(jsonObj.getString("lac_code"));
recordModel.setLat(String.valueOf(jsonObj.getDouble("lat")));
recordModel.setLon(String.valueOf(jsonObj.getDouble("lon")));
recordModel.setNcode(jsonObj.getString("ncode"));
recordModel.setRaduis(jsonObj.getString("radius"));
recordModel
.setWzbs(String.valueOf(jsonObj.getInt("loc_method")));
recordModel.setXhqd(jsonObj.getString("signal_strength"));
recordModel.setResult(jsonObj.getString("jiange"));// 存放间隔时间
recordModel.setBz(jsonObj.getString("yys"));// 备注字段存放运营商
list.add(recordModel);
db.updateToDb("T_RECORDS", list);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
}
/**
* 关闭数据库连接
*/
db.close_SqlDb();
String[] endUpStr = dateFormat.format(new Date()).split(":");
int endUpTime = 0;
currHour = 0;
currMin = 0;
try {
currHour = Integer.parseInt(endUpStr[0]);
currMin = Integer.parseInt(endUpStr[1]);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog("结束上报位置记录时间点,解析时间出现异常" + e.getMessage());
}
endUpTime = currHour * 60 + currMin;
// ******************************************************仅供记录日志******************************************************
if (loc.getDw_type() == 1) {
log = "位置上报的方式***结果:" + "卫星***" + res;
} else if (loc.getDw_type() == 3) {
log = "位置上报的方式***结果:" + "向Baidu请求成功***" + res;
} else if (loc.getDw_type() == -1) {
log = "位置上报的方式***结果:" + "向Baidu请求失败***" + res;
}
Log.i(TAG, log);
recordLog(log);
log = "上报流程共花费时间:" + String.valueOf(endUpTime - startUpTime) + "分钟";
Log.i(TAG, log);
recordLog(log);
}
/**
* 记录日志
*
* @param log
*/
public void recordLog(String log) {
shareMethd = new ShareMethod(JqgjService.this);
shareMethd.recordLxsbLog(log);
}
Handler mainHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
Toast.makeText(JqgjService.this, "GPS设备未打开,请打开执行连续上报!",
Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(JqgjService.this, "检查到没有可用的网络,请打开网络连接!",
Toast.LENGTH_LONG).show();
break;
case 2:
// 注册百度定位监听器
baidu = new Baidu_location(JqgjService.this);
}
super.handleMessage(msg);
}
};
/**
* 检测并关闭Gps设备
*/
public void closeGps() {
SystemInfo sys = new SystemInfo(JqgjService.this);
boolean flag = sys
.isServiceRunning("com.jqyd.shareInterface.GpsService");
if (flag) {
Intent intent = new Intent(JqgjService.this, GpsService.class);
stopService(intent);
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
recordLog("**********************onDestroy JqgjService**********************");
log = "连续上报服务被终止掉,释放资源";
Log.i(TAG, log);
recordLog(log);
// 连续上报--节省电量,释放资源
if (wakeLock != null) {// 保持深度休眠,在service停止运行的时候,释放wakelock锁
wakeLock.release();
wakeLock = null;
}
// 关闭GPS
closeGps();
freeBdListener();
// 重启当前服务,此方法只针对某些操作有用,如:终止服务。遇360等变态软件则无效
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recordLog(e.getMessage());
}
startService(new Intent(this, JqgjService.class));
recordLog("-----由于终止service导致重启启动service---------");
super.onDestroy();
}
@Override
public ComponentName startService(Intent service) {
// TODO Auto-generated method stub
return super.startService(service);
}
@Override
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
recordLog("**********************stopService**********************");
return super.stopService(name);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
// 销毁百度定位监听器
public void freeBdListener() {
if (baidu != null) {
baidu.stopListener();
baidu = null;
}
}
}