package com.jqyd.newprocess;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.jqyd.app.MyApp;
import com.jqyd.app.UpMyFile;
import com.jqyd.app.WriteFile;
import com.jqyd.manager.Login;
import com.jqyd.manager.MainActivity;
import com.jqyd.manager.R;
import com.jqyd.manager.Wdzt;
import com.jqyd.pub.JqydDateUtil;
import com.jqyd.pub.MyProgressDialog;
import com.jqyd.shareInterface.Contants;
import com.jqyd.shareInterface.GpsService;
import com.jqyd.shareInterface.Optdb_interfce;
import com.jqyd.shareInterface.Optsharepre_interface;
import com.jqyd.shareInterface.SystemInfo;
import com.jqyd.shareInterface.UpLocationService;
import com.jqyd.shareInterface.UpPlanService;
import com.jqyd.shareInterface.UpdataToServer;
import com.jqyd.son.DwKq;
import com.jqyd.son.Xgmm;
import com.jqyd.utils.ZipUtil;
public class MorePage extends Activity implements OnClickListener {
private TextView title;
private Button back;
private LinearLayout myState_layout;
private LinearLayout upPass_layout;
private LinearLayout maLoc_layout;
private LinearLayout seLoc_layout;
private LinearLayout seHisLoc_layout;
private LinearLayout opUpLoc_layout;
private LinearLayout deLogin_layout;
private LinearLayout right_layout;
private LinearLayout logUpLoad_layout;
private TableLayout xcgl_layout;
private LinearLayout update_layout;
private MyApp myApp;
private Optsharepre_interface share_obj = null;
private Optdb_interfce db = null;
// private ProgressDialog pd;
private AlertDialog.Builder ad;
private WriteFile wf;
private ArrayList<File> lastSevenDayLogs;
private Map<String, ArrayList<File>> dayMap = new HashMap<String, ArrayList<File>>();
private MyProgressDialog pbar;
private MyBroadcastReciver receiveBroadCast;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.morepage);
title = (TextView) this.findViewById(R.id.title);
title.setText("更多");
back = (Button) this.findViewById(R.id.back);
logUpLoad_layout = (LinearLayout) this
.findViewById(R.id.logUpLoad_layout);
myState_layout = (LinearLayout) this.findViewById(R.id.myState_layout);
upPass_layout = (LinearLayout) this.findViewById(R.id.upPass_layout);
maLoc_layout = (LinearLayout) this.findViewById(R.id.maLoc_layout);
seLoc_layout = (LinearLayout) this.findViewById(R.id.seLoc_layout);
seHisLoc_layout = (LinearLayout) this
.findViewById(R.id.seHisLoc_layout);
opUpLoc_layout = (LinearLayout) this.findViewById(R.id.opUpLoc_layout);
deLogin_layout = (LinearLayout) this.findViewById(R.id.deLogin_layout);
xcgl_layout = (TableLayout) this.findViewById(R.id.xcgl_layout);
right_layout = (LinearLayout) this.findViewById(R.id.right_layout);
update_layout = (LinearLayout) this.findViewById(R.id.update_layout);
right_layout.setVisibility(LinearLayout.INVISIBLE);
back.setOnClickListener(this);
myState_layout.setOnClickListener(this);
upPass_layout.setOnClickListener(this);
maLoc_layout.setOnClickListener(this);
seLoc_layout.setOnClickListener(this);
seHisLoc_layout.setOnClickListener(this);
opUpLoc_layout.setOnClickListener(this);
deLogin_layout.setOnClickListener(this);
update_layout.setOnClickListener(this);
logUpLoad_layout.setOnClickListener(this);
myApp = (MyApp) this.getApplication();
// pd = new ProgressDialog(MorePage.this);
share_obj = new Optsharepre_interface(MorePage.this);
wf = new WriteFile(MorePage.this, "MorePage"
+ JqydDateUtil.getDateDayOne(new Date()));
String gnjs_all = share_obj.getDataFromPres("GNJS");
if (!gnjs_all.contains("xcgl")) {
xcgl_layout.setVisibility(TableLayout.GONE);
}
}
Handler myHander = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case 1: // 正在执行
showDialog(1);
break;
case 2: // 成功
removeDialog(1);
Bundle bundle = msg.getData();
Toast.makeText(MorePage.this, bundle.getString("msg"),
Toast.LENGTH_SHORT).show();
break;
case 3: // 失败
removeDialog(1);
Bundle bundle2 = msg.getData();
if (bundle2.getString("msg").equals("请检查网络连接是否正常!")) {
Toast.makeText(MorePage.this, bundle2.getString("msg"),
Toast.LENGTH_SHORT).show();
} else {
cleanData();
Toast.makeText(MorePage.this,
bundle2.getString("msg") + ",请重新登录",
Toast.LENGTH_SHORT).show();
finish();
myApp.setIslogin(false);
startActivity(new Intent(MorePage.this, Login.class));
}
break;
case 10:
if (pbar != null) {
pbar.dismiss();
}
String s = (String) msg.obj;
if (s != null && !s.equals(""))
Toast.makeText(MorePage.this, s, Toast.LENGTH_SHORT).show();
// if (pd != null)
// pd.dismiss();
break;
case 11:// 日志上传成功
if (pbar != null) {
pbar.dismiss();
}
Toast.makeText(MorePage.this, "日志上传成功", Toast.LENGTH_SHORT)
.show();
// if (pd != null)
// pd.dismiss();
break;
case 12:// 日志上传失败
if (pbar != null) {
pbar.dismiss();
}
Toast.makeText(MorePage.this, "日志上传失败", Toast.LENGTH_SHORT)
.show();
// if (pd != null)
// pd.dismiss();
break;
case 13:// 没有日志文件
// if (pd != null)
// pd.dismiss();
if (pbar != null) {
pbar.dismiss();
}
Toast.makeText(MorePage.this, "没有文件", Toast.LENGTH_SHORT)
.show();
break;
case 14:// 开始上传日志,创建进度条
pbar = new MyProgressDialog(MorePage.this);
pbar.setMessage("正在上传日志");
pbar.setCancelable(false);
pbar.show();
break;
}
}
};
/**
* 数据清除
*
*/
private void cleanData() {
Optdb_interfce opt = new Optdb_interfce(this);
opt.deleteFromDb("ALL");
opt.close_SqlDb();
File file = new File("/data/data/" + this.getPackageName()
+ "/shared_prefs");
File file2 = this.getCacheDir();
share_obj.SharedClear();
if (file2 != null && file2.exists() && file2.isDirectory()) {
for (File item : file2.listFiles()) {
item.delete();
}
}
}
/**
* 数据更新线程
*
*/
class UpdateThread extends Thread {
String username;
String password;
String imsi;
String gnjs;
String timeNode;
String version;
String vercode;
public UpdateThread(String username, String password, String imsi,
String gnjs, String timeNode, String version) {
this.username = username;
this.password = password;
this.imsi = imsi;
this.gnjs = gnjs;
this.timeNode = timeNode;
this.version = version;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
Looper.prepare();
Message message1 = new Message();
message1.what = 1;
myHander.sendMessage(message1);
UpdataToServer server = new UpdataToServer(MorePage.this);
String Result = server.Update(username, password, imsi, gnjs,
timeNode, version, vercode);
Message message2 = new Message();
Bundle bundle = new Bundle();
String rets[] = Result.split("#");
if (rets[0].equals("0")) {// 更新成功
bundle.putString("msg", "数据更新成功");
message2.setData(bundle);
message2.what = 2;
} else {
bundle.putString("msg", rets[1]);
message2.what = 3;
}
message2.setData(bundle);
myHander.sendMessage(message2);
Looper.loop();
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
// 初始化共享池中的数据
myApp.setGroupNums("");// 分组编号
}
@SuppressLint("NewApi")
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
if (view == myState_layout) {
startActivity(new Intent().setClass(this, Wdzt.class));
} else if (view == upPass_layout) {
startActivity(new Intent().setClass(this, Xgmm.class));
} else if (view == maLoc_layout) {
startActivity(new Intent(this, DwKq.class).putExtra("moduleName",
"dwgl"));
} else if (view == seLoc_layout) {
myApp.setModuleName("wzcx");
startActivity(new Intent().setClass(this, EmpGroupList.class));
} else if (view == seHisLoc_layout) {
myApp.setModuleName("gjhf");
startActivity(new Intent().setClass(this, EmpGroupList.class));
} else if (view == opUpLoc_layout) {
// 启动连续上报
// Intent stateService = new Intent(this,
// JqgjService.class);
// startService(stateService);
if (!myApp.isServiceRunning()) {
wf.writeToFile("连续上报未启动服务,开始启动服务");
startService(new Intent(MorePage.this, UpPlanService.class));
startService(new Intent(MorePage.this, UpLocationService.class));
}
if (myApp.isServiceRunning()) {
wf.writeToFile("连续上报服务已经启动");
Toast.makeText(MorePage.this, "连续上报服务已经启动……",
Toast.LENGTH_SHORT).show();
} else {
wf.writeToFile("连续上报服务未启动");
Toast.makeText(MorePage.this, "请再试一次……", Toast.LENGTH_SHORT)
.show();
}
} else if (view == deLogin_layout) {
exit();
} else if (view == back) {
startActivity(new Intent().setClass(MorePage.this,
MainActivity.class));
} else if (view == update_layout) {
db = new Optdb_interfce(MorePage.this);
String loginNameStr = share_obj.getDataFromPres("REGSIM");
String pwdStr = share_obj.getDataFromPres("password");
String timeNode = "19000101";
ArrayList<Object> list = new ArrayList<Object>();
try {
list = db.searchFromDb("DATA_UPDATES");
// 关闭数据库
db.close_SqlDb();
} catch (Exception e) {
// TODO Auto-generated catch block
}
if (list.size() > 0) {
timeNode = "";
for (int i = 0; i < list.size(); i++) {
timeNode += list.get(i) + "#";
}
timeNode = timeNode.substring(0, timeNode.length() - 1);
}
String values = share_obj.getDataFromPres("LOGIN");
String vals[] = values.split("#");
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imsi = tm.getSubscriberId(); // 取出现在的IMSI号码
if (imsi == null) {
imsi = "000000000000000";
}
new UpdateThread(loginNameStr, pwdStr, imsi, vals[0], timeNode,
myApp.getVersion()).start();
} else if (view == logUpLoad_layout) {
// 错误日志上传
dayMap.clear();
String path = Contants.LogPath;
File file = new File(path);
if (!file.exists()) {
myHander.sendMessage(Message.obtain(myHander, 10, "没有文件"));
}
// 遍历文件夹(包括子文件夹)下的文件
lastSevenDayLogs = listFile(file, new ArrayList<File>());
if (lastSevenDayLogs == null || lastSevenDayLogs.size() == 0) {
// 如果没有文件就提示用户
myHander.sendMessage(Message.obtain(myHander, 13));
} else {// 如果有文件,就对文件按日期进行分配,放入map集合中
for (int i = 0; i < lastSevenDayLogs.size(); i++) {
File newfile = lastSevenDayLogs.get(i);
// 取出文件命中所包含的日期
String time = returnTimeforLogFile(newfile);
if (!dayMap.containsKey(time)) {// 如果map中没有此日期的文件,则添加
dayMap.put(time, new ArrayList<File>());
}
dayMap.get(time).add(newfile);// 将文件加入map中对应的位置
}
// 将所有文件分配到map中以后,清除lastSevenDayLogs,为下次使用做准备
lastSevenDayLogs.clear();
/* 将所有的日期放入一个数组,进行排序后,取出最近的7个日期 */
String[] arr = dayMap.keySet().toArray(
new String[dayMap.size()]);
Arrays.sort(arr);
final String[] nowArr = Arrays.copyOfRange(arr,
arr.length > 7 ? arr.length - 7 : 0, arr.length);
ad = new AlertDialog.Builder(MorePage.this);
ad.setMultiChoiceItems(nowArr, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
Log.e("选择的日期", nowArr[which]);
// 将用户选择的文件放入已经清除过的lastSevenDayLogs中
if (isChecked) {
lastSevenDayLogs.addAll(dayMap
.get(nowArr[which]));
} else {
if (lastSevenDayLogs.containsAll(dayMap
.get(nowArr[which]))) {
lastSevenDayLogs.removeAll(dayMap
.get(nowArr[which]));
}
}
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
})
.setNeutralButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// 开始上传线程
Log.e("确定按钮点击", "确定按钮点击");
new UpLoadLogsByOneThread().start();
// pd.setMessage("上传中...");
// pd.show();
}
});
ad.create().show();
}
}
}
/**
*
* @param file
* 要解析的文件夹
* @param logFiles
* 用于缓存文件列表
* @return
*/
private ArrayList<File> listFile(File file, ArrayList<File> logFiles) {
if (file.isDirectory()) {
File[] t = file.listFiles();
for (int i = 0; i < t.length; i++) {
listFile(t[i], logFiles);
}
} else {
logFiles.add(file);
}
return logFiles;
}
/**
* 将7天内用户选择日期的日志打成一个包进行上传.
*
* @author Administrator
*
*/
class UpLoadLogsByOneThread extends Thread {
@Override
public void run() {
if (lastSevenDayLogs.size() > 0) {// 判断用户是否选择文件
registerRec();// 注册广播接收者
File logsZip = ZipLogs();// 如果有,就将用户选择的文件进行打包
if (logsZip != null && logsZip.exists()) {
myHander.sendEmptyMessage(14);// 显示进度条
try {
Thread.sleep(500);// 延时以避免pbar出现空指针
} catch (InterruptedException e) {
e.printStackTrace();
}
uploadLogs(logsZip);// 存在就上传
} else {// 表示打包没有成功,提示用户上传失败
myHander.sendMessage(Message.obtain(myHander, 12));
}
} else {// 表示用户没有选择文件,提示用户
myHander.sendMessage(Message.obtain(myHander, 10, "请勾选至少一个日期"));
}
}
/**
* 注册接收上传日志进度的广播接收者
*/
public void registerRec() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("upfile");
receiveBroadCast = new MyBroadcastReciver();
MorePage.this.registerReceiver(receiveBroadCast, intentFilter);
}
/**
* 将用户选择的日志进行打包,命名格式:"REGSIM"_RZ.zip 例:13637112345_RZ.zip
*
* @return 打包好的zip文件.如果打包失败则返回null
*/
private File ZipLogs() {
File logsZip = null;
String zipName = share_obj.getDataFromPres("REGSIM") + "_RZ.zip";
logsZip = new File(Contants.LogPath, zipName);
try {
ZipUtil.zipFiles(lastSevenDayLogs, logsZip);
} catch (IOException e) {
return null;
}
return logsZip;
}
/**
* 对打包好的日志进行上传
*
* @param logsZip
* 打包好的日志
*/
private void uploadLogs(File logsZip) {
Bundle bundle = new Bundle();
String absPath = logsZip.getAbsolutePath();
String fileName = absPath.split("/")[absPath.split("/").length - 1];
bundle.putString("guid", share_obj.getDataFromPres("GUID"));
bundle.putString("regsim", share_obj.getDataFromPres("REGSIM"));
bundle.putString("xxbt", fileName);
bundle.putString("imagePath", absPath);
UpMyFile upFile = new UpMyFile(MorePage.this);
int uplength = (int) logsZip.length();
pbar.setMax(uplength/1024);//设置进度条的最大值
String result = upFile.upToServer(bundle, "errorLogs");
logsZip.delete();// 上传以后,删除zip文件
if (result != null && result.equals("0")) {// 表示上传成功
myHander.sendMessage(Message.obtain(myHander, 11));
} else {// 表示上传失败
myHander.sendMessage(Message.obtain(myHander, 12));
}
}
}
/**
* 广播接收者,用于接收文件上传的进度
*
* @author Administrator
*
*/
private class MyBroadcastReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (action.equals("upfile")) {
// int max = intent.getIntExtra("max", 0);
// if (pbar != null) {
// pbar.setMax(max/1024);
// }
int length = intent.getIntExtra("length", 0);
if (pbar != null) {
pbar.setProgress(length / 1024);
}
}
}
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
ProgressDialog dialog = new ProgressDialog(MorePage.this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
switch (id) {
case 1:
dialog.setMessage("正在更新数据,请稍候……");
break;
}
return dialog;
}
@Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
// 这种方式好像Google最新的官方已经不支持了,没有restartPackage方法了
try {
ActivityManager aMgr = (ActivityManager) this
.getSystemService(ACTIVITY_SERVICE);
aMgr.restartPackage(getPackageName());
Log.i("More", "完美退出");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("More", "退出出现异常");
}
}
/**
* 点击注销登录
*/
public void exit() {
new AlertDialog.Builder(this)
.setTitle("注意")
.setMessage("确认注销登录?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
closeGps();
myApp.setIslogin(false);
finish();
startActivity(new Intent(MorePage.this, Login.class));
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
/**
* 检测并关闭Gps设备
*/
public void closeGps() {
SystemInfo sys = new SystemInfo(this);
boolean flag = sys
.isServiceRunning("com.jqyd.shareInterface.GpsService");
if (flag) {
Intent intent = new Intent(this, GpsService.class);
stopService(intent);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
startActivity(new Intent().setClass(MorePage.this,
MainActivity.class));
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* 返回文件名中的时间
*
* @param file
* @return
* @author zst
*/
private String returnTimeforLogFile(File file) {
String time = "";
String name = file.getName();
if (!file.isDirectory() && name.length() > 14) {
int start = name.length() - 14;
int end = name.length() - 4;
time = name.substring(start, end);
}
return time;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (receiveBroadCast != null) {
MorePage.this.unregisterReceiver(receiveBroadCast);// 注销广播接收者
}
}
}