Newer
Older
dxcgt / app / src / main / java / com / smartdot / cgt / activity / FrmMain.java
wangxitong on 6 Apr 2021 53 KB first commit
package com.smartdot.cgt.activity;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
//import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.SensorManager;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.TelephonyManager;
import android.text.TextPaint;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smartdot.cgt.R;
import com.smartdot.cgt.adapter.MainViewPagerAdapter;
import com.smartdot.cgt.receiver.MyJgtsUIUpdateReceiver;
import com.smartdot.cgt.request.ApiClent;
import com.smartdot.cgt.util.ApplicationMain;
import com.smartdot.cgt.util.BaseThread;
import com.smartdot.cgt.util.FileUtils;
import com.smartdot.cgt.util.GisUtil;
import com.smartdot.cgt.util.GpsManager;
import com.smartdot.cgt.util.HandlerStatus;
import com.smartdot.cgt.util.LoginVo;
import com.smartdot.cgt.util.Msg;
import com.smartdot.cgt.util.PerformanceUtil;
import com.smartdot.cgt.util.config.CgtConfig;
import com.smartdot.cgt.view.PageControlView;



public class FrmMain extends BaseActivity
{
	public static final String NEEDAUTOUPDATEKEY = "NEEDAUTOUPDATEKEY";
	private static final int DELAY = SensorManager.SENSOR_DELAY_NORMAL;
	private boolean showedNotification = false;
	private View btn_ProblemInput;
	private View btn_ProblemInput1;
	private View btn_ProblemCheck;
	private View btn_ProblemReCheck;
	private View btn_MapView;
	private View btn_ProblemHistory,btn_ProblemHistory1,btn_ProblemHistory2;
	private View btn_MyTask;
	private View btn_MsgAlert;
	private View btn_DataSync;
	private View btnDial;
	private View btn_Setting,btn_Setting1,btn_Setting2;
	private View btn_Help;
	private View btn_TakeOff;
	private View btn_QuickInput;
	private View btn_ThreeInput;
	private View btn_mqsb;
	private View pwdUpdate;
	private View txlPhone;
	private View kqgl;
	private View btn_analysis,btn_ProblemHandle,btn_ProblemUrgent,
				btn_PersonOnline,btn_OverTime;
	//private JPushReceiver dianLiangBR;
	//	private View btn_mqsbhc;
	//private View btn_Construct;
	public boolean createFlag = false;
	private BaseThread msgTaskLoopThread;
	private List<BaseThread> threadList = new ArrayList<BaseThread>();
	// 新增控件
	private ViewPager viewPager;
	private List<View> views;
	private View view1,view2,view3;
	private PageControlView pageControlView;
	private ImageView imgMessage;
	private ImageView imguser;
	private RelativeLayout mainhome;
	private RelativeLayout mainmsg;
	private RelativeLayout mainphone;
	private RelativeLayout mainme;
	private TextView main_headId,main_headId1;
	private static final int PHOTO_REQUEST_TAKEPHOTO = 5001;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 5002;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 5003;// 结果
	private static final String FILEPATH = "/sdcard/cgt/user.jpg";// 结果
//	private int gpscount=0;
//	private UserModel user=ApplicationMain.getInstance().getUserModel();
	// 创建一个以当前时间为名称的文件
	File tempFile = new File(Environment.getExternalStorageDirectory(),
			getPhotoFileName());

	@Override
	protected void setLayout()
	{
		initActivity();
		setContentView(R.layout.main);
		// 新增控件
		imgMessage = (ImageView) findViewById(R.id.imgMessage);
		imguser = (ImageView) findViewById(R.id.main_user);
		mainhome = (RelativeLayout) findViewById(R.id.rl_home);
		mainmsg = (RelativeLayout) findViewById(R.id.btn_MsgAlert);
		mainphone = (RelativeLayout) findViewById(R.id.txlPhone);
		mainme = (RelativeLayout) findViewById(R.id.btn_Me);

		pageControlView = (PageControlView) findViewById(R.id.pageControlView);
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		views = new ArrayList<View>();
		LayoutInflater inflater = getLayoutInflater();
		view1 = inflater.inflate(R.layout.main_view_first, null);
		view2 = inflater.inflate(R.layout.main_view_second, null);
		view3 = inflater.inflate(R.layout.main_view_third, null);
		//权限设置
		String roleTip = PerformanceUtil.getUser(FrmMain.this).getRoleTip();
		if(roleTip.equals("supervisor")){
			views.add(view1);
		}else if(roleTip.equals("process")){
			views.add(view2);
		}else if(roleTip.equals("leader")){
			views.add(view3);
		}else {
			Msg.showInfo(FrmMain.this, "您暂无使用权限");
			finish();
		}

		viewPager.setAdapter(new MainViewPagerAdapter(views));
		viewPager.setCurrentItem(0);
//		viewPager.setOnPageChangeListener(new MyOnPageChangeListener());
		pageControlView.setCount(views.size());
		Intent intent = getIntent();
//		String pageS = intent.getStringExtra("pageS");
//		if("pageS".equals(pageS))
//		{
//			viewPager.setCurrentItem(1);
//			pageControlView.generatePageControl(1);
//		}else
//		{
//			pageControlView.generatePageControl(0);
//		}

		main_headId = (TextView) findViewById(R.id.main_headId);
		main_headId1 = (TextView) findViewById(R.id.main_headId1);
		btn_ProblemInput = (View) view1.findViewById(R.id.btn_ProblemInput);
		btn_ProblemInput1 = (View) view3.findViewById(R.id.btn_ProblemInput);
		btn_ProblemCheck = (View) view1.findViewById(R.id.btn_ProblemCheck);
		btn_ProblemReCheck = (View) view1.findViewById(R.id.btn_ProblemReCheck);

		btn_ProblemHistory = (View) view1.findViewById(R.id.btn_ProblemHistory);
		btn_ProblemHistory1 = (View) view2.findViewById(R.id.btn_ProblemHistory);
		btn_ProblemHistory2 = (View) view3.findViewById(R.id.btn_ProblemHistory);
		btn_QuickInput = (View) view1.findViewById(R.id.btn_QuickInput);
		btn_ThreeInput = (View) view1.findViewById(R.id.btn_ThreeInput);
		btn_Setting = (View) view1.findViewById(R.id.btn_Setting);
		btn_Setting1 = (View) view2.findViewById(R.id.btn_Setting);
		btn_Setting2 = (View) view3.findViewById(R.id.btn_Setting);
		btn_ProblemHandle = (View) view2.findViewById(R.id.btn_ProblemHandle);
		btn_analysis = (View) view3.findViewById(R.id.btn_Analysis);
		btn_PersonOnline = (View) view3.findViewById(R.id.btn_PersonOnline);
		btn_ProblemUrgent = (View) view3.findViewById(R.id.btn_ProblemUrgent);
		btn_OverTime = (View) view3.findViewById(R.id.btn_OverTime);
		main_headId.setText(PerformanceUtil.getUser(FrmMain.this).getAdminname());
		String role = "";
		if(PerformanceUtil.getUser(FrmMain.this).getRoleTip().equals("supervisor")){
			role = "监督人员";
		}else if(PerformanceUtil.getUser(FrmMain.this).getRoleTip().equals("process")){
			role = "处置人员";
		}else if(PerformanceUtil.getUser(FrmMain.this).getRoleTip().equals("leader")){
			role = "局领导";
		}
		main_headId1.setText(PerformanceUtil.getUser(FrmMain.this).getDeptName() + role);
		createFlag = true;
	}

	@Override
	protected void doInit()
	{
		if (FileUtils.isFileExists(FILEPATH))
		{
			Bitmap bitmap = BitmapFactory.decodeFile(FILEPATH);
			imguser.setImageBitmap(bitmap);
		}
		getBgPoints();
		GpsManager.getGpsSingerton().startGps(this);
		Intent intent = this.getIntent();
		if (intent != null)
		{
			Bundle bundle = intent.getExtras();
			if (bundle != null)
			{
				if (bundle.getBoolean(NEEDAUTOUPDATEKEY, false))
				{
//					autoUpdateCacheData();
				}
			}
		}

//		autoCheckConfig();
		getMsgAndTask();
//		intMsg(); //小红点
		//  PollingUtils.startPollingService(this, 120, PollingService.class, PollingService.ACTION);
	}
//	public void intMsg()
//	{
//
//		try {
//			showDeal(Integer.valueOf(ApplicationMain.getInstance().getUserModel().getDealNum()));
//			showHc(Integer.valueOf(ApplicationMain.getInstance().getUserModel().getHcNum()));
//			showHs(Integer.valueOf(ApplicationMain.getInstance().getUserModel().getHsNum()));
//			showMessage(Integer.valueOf(ApplicationMain.getInstance().getUserModel().getMsgNum()));
//		}catch (Exception e)
//		{
//
//		}
//	}



	public void reportGpsPosition1() {

//		showNotification();
	    String timeStr = null;
		Location location=	GpsManager.getGpsSingerton().getLocation();
		String longitude="0";
		String latitude="0" ;
		if(location!=null)
		{
			 Double b0=location.getLongitude();
	            double b3=0;
	            if(b0!=null&&!"".equals(b0)) {
					b3= b0;
	            }
			longitude= String.valueOf(b3);
			latitude= Double.toString(location.getLatitude());
		try {
			 StringBuffer sb = new StringBuffer(256);
				sb.append("longitude : "+longitude);
				sb.append("latitude : "+latitude);
				File configFolder = new File(Environment.getExternalStorageDirectory().getPath() + "/cgt/");
				if (!configFolder.exists())
				{
					configFolder.mkdirs();
				}
				File errLog = new File(configFolder, "GPS.log");
				try
				{
					if (!errLog.exists()) {
						errLog.createNewFile();
					}
					OutputStream os = new FileOutputStream(errLog, true);
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("{MM-dd HH:mm:ss.SSS}", Locale.CHINA);
					timeStr = simpleDateFormat.format(System.currentTimeMillis());
					os.write(EncodingUtils.getBytes(timeStr + sb.toString()+"\n", "UTF-8"));
					os.flush();
					os.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}

				String userId="";
				if(ApplicationMain.getInstance()!=null&&ApplicationMain.getInstance().getUserModel()!=null&&ApplicationMain.getInstance().getUserModel().getBgAdminId()!=null)
				{
					userId=ApplicationMain.getInstance().getUserModel().getBgAdminId();
				}else{
					LoginVo vo=	PerformanceUtil.getUser(FrmMain.this);
					userId=vo.getBgadminid();
				}
			TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
			final String deviceId = tm.getDeviceId();
			ApiClent.positionUpload(deviceId,longitude,latitude,new ApiClent.ClientCallback() {
				@Override
				public void onSuccess(Object data)
				{
					try {
						JSONObject jsonObject = new JSONObject(data.toString());
						System.out.println("*************定位信息上传:"+jsonObject + "*************");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Log.i("positionUpload_error", e.getMessage());
					}
				}
				@Override
				public void onFailure(String message) {

				}
				@Override
				public void onError(Exception e) {

				}
			});

		} catch (Exception e) {
			File configFolder = new File(Environment.getExternalStorageDirectory().getPath() + "/cgt/");
			if (!configFolder.exists())
			{
				configFolder.mkdirs();
			}
			File errLog = new File(configFolder, "PollingService.log");
			 StringBuffer sb = new StringBuffer(256);
			try
			{
				if (!errLog.exists())
				{
					errLog.createNewFile();
				}
				OutputStream os = new FileOutputStream(errLog, true);
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("{MM-dd HH:mm:ss.SSS}", Locale.CHINA);
				 timeStr = simpleDateFormat.format(System.currentTimeMillis());
				sb.append("------PollingService------"+e.getMessage());
				os.write(EncodingUtils.getBytes(timeStr + sb.toString()+"\n", "UTF-8"));
				os.flush();
				os.close();
			}
			catch (IOException e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	  }
		else{
			Msg.showInfo(FrmMain.this, "未打开定位,无法上传定位信息");
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		MyApplication.getInstance().addActivity(this);
//		 if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
//	            //结束你的activity
//	            finish();
//	            return;
//	        }
		MyJgtsUIUpdateReceiver mReceiver = new MyJgtsUIUpdateReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
//				if(intent.getAction().equals("com.dessert.mojito.JGTS")) {
//					Bundle bundle = (Bundle)intent.getBundleExtra("jgts");
//					for (String key : bundle.keySet())
//					{
//						if (key.equals(JPushInterface.EXTRA_EXTRA))
//						{
//							if (StringUtils
//									.isNullOrEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA)))
//							{
//								Log.i(TAG, "This message has no Extra data");
//								continue;
//							}
//
//							try
//							{
//								JSONObject json = new JSONObject(
//										bundle.getString(JPushInterface.EXTRA_EXTRA));
//								Iterator<String> it = json.keys();
//
//								while (it.hasNext())
//								{
//									String myKey = it.next().toString();
//
//									if("dealNum".equals(myKey))
//									{
//										String dealNum=json.optString(myKey);
//										if(dealNum!=null&&!"".equals(dealNum))
//										{
//											showDeal(Integer.valueOf(dealNum));
//										}
//
//									}else if("hcNum".equals(myKey))
//									{
//										String hcNum=json.optString(myKey);
//										if(hcNum!=null&&!"".equals(hcNum))
//										{
//											showHc(Integer.valueOf(hcNum));
//										}
//
//									}else if("hsNum".equals(myKey))
//									{
//										String hsNum=json.optString(myKey);
//										if(hsNum!=null&&!"".equals(hsNum))
//										{
//											showHs(Integer.valueOf(hsNum));
//										}
//									}else if("msgNum".equals(myKey))
//									{
//										String msgNum=json.optString(myKey);
//										if(msgNum!=null&&!"".equals(msgNum))
//										{
//											showMessage(Integer.valueOf(msgNum));
//										}
//									}
//
//								}
//							}
//							catch (JSONException e)
//							{
//								Log.e(TAG, "Get message extra JSON error!");
//							}
//
//						}
//					}
//				}
			}
		};
//		IntentFilter filter = new IntentFilter();
//		filter.addAction("com.dessert.mojito.JGTS");
//		registerReceiver(mReceiver, filter);
	}

	@Override
	protected void addEventListener()
	{
		btn_ProblemInput.setOnClickListener(btnClickListener);
		btn_ProblemInput1.setOnClickListener(btnClickListener);
		btn_ProblemCheck.setOnClickListener(btnClickListener);
		btn_ProblemReCheck.setOnClickListener(btnClickListener);
		btn_ProblemHistory.setOnClickListener(btnClickListener);
		btn_ProblemHistory1.setOnClickListener(btnClickListener);
		btn_ProblemHistory2.setOnClickListener(btnClickListener);
		btn_Setting.setOnClickListener(btnClickListener);
		btn_Setting1.setOnClickListener(btnClickListener);
		btn_Setting2.setOnClickListener(btnClickListener);
		btn_QuickInput.setOnClickListener(btnClickListener);
		btn_ThreeInput.setOnClickListener(btnClickListener);
		btn_analysis.setOnClickListener(btnClickListener);
		btn_PersonOnline.setOnClickListener(btnClickListener);
		btn_ProblemUrgent.setOnClickListener(btnClickListener);
		btn_OverTime.setOnClickListener(btnClickListener);
		btn_ProblemHandle.setOnClickListener(btnClickListener);
		imgMessage.setOnClickListener(btnClickListener);
		imguser.setOnClickListener(btnClickListener);
		mainme.setOnClickListener(btnClickListener);
		mainphone.setOnClickListener(btnClickListener);
	}

	@Override
	protected void doDestroy()
	{
		GpsManager.getGpsSingerton().stopGps();
		if (msgTaskLoopThread != null)
		{
			msgTaskLoopThread.interrupt();
		}

//		 PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
			case PHOTO_REQUEST_TAKEPHOTO:// 当选择拍照时调用
				startPhotoZoom(Uri.fromFile(tempFile), 150);
				break;

			case PHOTO_REQUEST_GALLERY:// 当选择从本地获取图片时
				// 做非空判断,当我们觉得不满意想重新剪裁的时候便不会报异常,下同
				if (data != null)
					startPhotoZoom(data.getData(), 150);
				break;

			case PHOTO_REQUEST_CUT:// 返回的结果
				if (data != null)
					setPicToView(data);
				break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}



//	class MyOnPageChangeListener implements OnPageChangeListener
//	{
//
//		@Override
//		public void onPageScrollStateChanged(int arg0)
//		{
//
//		}
//
//		@Override
//		public void onPageScrolled(int arg0, float arg1, int arg2)
//		{
//
//		}
//
//		@Override
//		public void onPageSelected(int arg0)
//		{
//			pageControlView.generatePageControl(arg0);
//		}
//	}

	private OnClickListener btnClickListener = new OnClickListener()
	{
		@Override
		public void onClick(View arg0)
		{
			// 案卷上报
			if (arg0 == btn_ProblemInput)
			{
				Intent intent = new Intent(FrmMain.this, FrmProblemInput.class);
				Bundle bundle = new Bundle();
				bundle.putString("caseSource","2");
				intent.putExtras(bundle);
				startActivity(intent);

			}else if (arg0 == btn_ProblemInput1)
			{
				Intent intent = new Intent(FrmMain.this, FrmProblemInput.class);
				Bundle bundle = new Bundle();
				bundle.putString("caseSource","6");
				intent.putExtras(bundle);
				startActivity(intent);

			}
			else if (arg0 == btn_mqsb)
			{
				   Intent intent= new Intent();
	                intent.setAction(Intent.ACTION_VIEW);

	                Uri content_url = Uri.parse(ApplicationMain.getInstance().getCgtConfig().getRequestUrl()+"pda.jsp");
	                intent.setData(content_url);
	                startActivity(intent);

			}
//			else	if (arg0 == btn_mqsbhc)
//			{
//				Intent intent = new Intent(FrmMain.this, FrmSanBaoCheck.class);
//				startActivity(intent);
//			}
			// 案卷核实
			else if (arg0 == btn_ProblemCheck)
			{
				Intent intent = new Intent(FrmMain.this, FrmProblemCheck.class);
				startActivity(intent);
			}
			// 案卷核查
			else if (arg0 == btn_ProblemReCheck)
			{
				Intent intent = new Intent(FrmMain.this,
						FrmProblemReCheck.class);
				startActivity(intent);
			}
			// 案卷查询
			else if (arg0 == btn_ProblemHistory||arg0 == btn_ProblemHistory1||arg0 == btn_ProblemHistory2)
			{
				Intent intent = new Intent(FrmMain.this, FrmProblemHistroy.class);
				startActivity(intent);
			}
			// 我的任务
			else if (arg0 == btn_MyTask)
			{
				Intent intent = new Intent(FrmMain.this, FrmMyTask.class);
				startActivity(intent);
			}
			// 我的消息
//			else if (arg0 == btn_MsgAlert)
//			{
//				Intent intent = new Intent(FrmMain.this, FrmMessageAlert.class);
//				startActivity(intent);
//			}
//			// 数据同步
//			else if (arg0 == btn_DataSync)
//			{
//				Intent intent = new Intent(FrmMain.this, FrmDataSync.class);
//				startActivity(intent);
//			}
//			// 单键拨号
			else if (arg0 == btnDial)
			{
				String userId="";
				if(ApplicationMain.getInstance()!=null&&ApplicationMain.getInstance().getUserModel()!=null&&ApplicationMain.getInstance().getUserModel().getBgAdminId()!=null)
				{
					userId=ApplicationMain.getInstance().getUserModel().getBgAdminId();
				}else{
					LoginVo vo=	PerformanceUtil.getUser(FrmMain.this);
					userId=vo.getBgadminid();
				}
				Intent intent = new Intent(FrmMain.this, JavaScriptInterfaceDemoActivity.class);
                intent.putExtra("userId",userId);
//				Intent intent= new Intent();
//				intent.setAction(Intent.ACTION_VIEW);
//				String requestUrl = ApplicationMain.getInstance().getCgtConfig().getRequestUrl();
//				Uri content_url = Uri.parse(requestUrl+"pwas/Case-fzgn.action?pdaid="+userId);
//				intent.setData(content_url);
				startActivity(intent);


			}else if (arg0 == txlPhone)
			{
				String userId="";
				if(ApplicationMain.getInstance()!=null&&ApplicationMain.getInstance().getUserModel()!=null&&ApplicationMain.getInstance().getUserModel().getBgAdminId()!=null)
				{
					userId=ApplicationMain.getInstance().getUserModel().getBgAdminId();
				}else{
					LoginVo vo=	PerformanceUtil.getUser(FrmMain.this);
					userId=vo.getBgadminid();
				}
				Intent intent = new Intent(FrmMain.this, JavaPhoneActivity.class);
				intent.putExtra("userId",userId);
				startActivity(intent);


			}else if (arg0 == txlPhone)
			{
				String userId="";
				if(ApplicationMain.getInstance()!=null&&ApplicationMain.getInstance().getUserModel()!=null&&ApplicationMain.getInstance().getUserModel().getBgAdminId()!=null)
				{
					userId=ApplicationMain.getInstance().getUserModel().getBgAdminId();
				}else{
					LoginVo vo=	PerformanceUtil.getUser(FrmMain.this);
					userId=vo.getBgadminid();
				}
				Intent intent = new Intent(FrmMain.this, JavaPhoneActivity.class);
				intent.putExtra("userId",userId);
				startActivity(intent);


			}else if (arg0 == kqgl)
			{
				String userId="";
				if(ApplicationMain.getInstance()!=null&&ApplicationMain.getInstance().getUserModel()!=null&&ApplicationMain.getInstance().getUserModel().getBgAdminId()!=null)
				{
					userId=ApplicationMain.getInstance().getUserModel().getBgAdminId();
				}else{
					LoginVo vo=	PerformanceUtil.getUser(FrmMain.this);
					userId=vo.getBgadminid();
				}
				Intent intent = new Intent(FrmMain.this, JavakqActivity.class);
				intent.putExtra("userId",userId);
				startActivity(intent);


			}
//			// 系统设置
			else if (arg0 == btn_Setting|| arg0 == btn_Setting1 || arg0 == btn_Setting2)
			{
				Intent intent = new Intent(FrmMain.this, FrmSetting.class);
				startActivity(intent);
			}else if (arg0 == pwdUpdate)
			{
				Intent intent = new Intent(FrmMain.this, FrmPwd.class);
				startActivity(intent);
			}
			// 系统帮助
			else if (arg0 == btn_Help)
			{
				Intent intent = new Intent(FrmMain.this, FrmHelp.class);
				startActivity(intent);
			}
			// 快速上报
			else if (arg0 == btn_QuickInput)
			{
				Intent intent = new Intent(FrmMain.this, FrmQuickInput.class);
				startActivity(intent);
			}else if (arg0 == btn_ThreeInput)
			{
				Intent intent = new Intent(FrmMain.this, FrmSanBaoInput.class);
				startActivity(intent);
			}
			// 下班打卡
			else if (arg0 == btn_TakeOff)
			{
				Intent intent = new Intent(FrmMain.this, FrmTakeOff.class);
				startActivity(intent);
			}
			else if (arg0 == btn_analysis)
			{
				Intent intent = new Intent(FrmMain.this, FrmAnalysis.class);
				startActivity(intent);
			}else if (arg0 == btn_PersonOnline)
			{
				Intent intent = new Intent(FrmMain.this, FrmPersonOnline.class);
				startActivity(intent);
			}else if (arg0 == btn_ProblemUrgent)
			{
				Intent intent = new Intent(FrmMain.this, FrmProblemSupervise.class);
				Bundle bundle = new Bundle();
				bundle.putString("title","urgent");
				intent.putExtras(bundle);
				startActivity(intent);
			}else if (arg0 == btn_OverTime)
			{
				Intent intent = new Intent(FrmMain.this, FrmProblemSupervise.class);
				Bundle bundle = new Bundle();
				bundle.putString("title","overtime");
				intent.putExtras(bundle);
				startActivity(intent);
			}else if( arg0 == btn_ProblemHandle){
				Intent intent = new Intent(FrmMain.this, FrmProblemHandle.class);
				startActivity(intent);
			}
			// 施工处理
			//else if (arg0 == btn_Construct)
			//{
			//	Intent intent = new Intent(FrmMain.this, FrmConstruct.class);
			//	startActivity(intent);
			//}
//			else if (arg0 == imgMessage)
//			{
//				Intent intent = new Intent(FrmMain.this, FrmMessageAlert.class);
//				startActivity(intent);
//			}
			// 用户头像点击事件
			else if (arg0 == imguser)
			{
				showDialog();
			}
			else if (arg0 == mainme)
			{
				Intent intent = new Intent(FrmMain.this, UserInfoActivity.class);
				startActivity(intent);
			}
			else if (arg0 == mainphone)
			{
				Intent intent = new Intent(FrmMain.this, FrmMailList.class);
				startActivity(intent);
			}

		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if(keyCode == KeyEvent.KEYCODE_BACK)
			{
				exitBy2Click(); //调用双击退出函数
			}
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 双击退出函数
	 */
	private static Boolean isExit = false;

	private void exitBy2Click() {
		Timer tExit = null;
		if (!isExit) {
			isExit = true; // 准备退出
			Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			tExit = new Timer();
			tExit.schedule(new TimerTask() {
				@Override
				public void run() {
					isExit = false; // 取消退出
				}
			}, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务

		} else {
			finish();
			System.exit(0);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void handleMessage(Message msg)
	{
		if (msg.what == HandlerStatus.getMsgAndTask)
		{
			if (msg.arg1 == HandlerStatus.HANDLE_OK)
			{
//				if (msg.obj != null)
//				{
//					CaseTaskNum task = ((ResponseResult<CaseTaskNum>) msg.obj).getResultObj();
//					if(task!=null){
//						//我的消息============
//						int messageCount= task.getMessage();
//						// txtMessage.setText(messageCount + "×");
//						if (messageCount > 0)
//						{
//							String msgContent = "您有" + messageCount + "条未阅读的消息!";
//							if (!NotificationCreater
//									.isNotificationAvailable(R.drawable.notification_msg))
//							{
//								NotificationCreater.createNotification(
//										FrmMain.this, new Intent(FrmMain.this,
//												FrmMessageAlert.class),
//										R.drawable.notification_msg, msgContent,
//										"城管通消息提醒", msgContent);
//							}
//							showMessage(messageCount);
//						}else
//						{
//							showMessage(0);
//						}
//						//我的核实============
//						int taskCount=task.getHs();
//						// txtTask.setText(taskCount + "×");
//						if (taskCount > 0)
//						{
//							String msgContent = "您有" + taskCount + "个未核实的任务!";
//							if (!NotificationCreater
//									.isNotificationAvailable(R.drawable.notification_task))
//							{
//								NotificationCreater.createNotification(
//										FrmMain.this, new Intent(FrmMain.this,
//												FrmMyTask.class),
//										R.drawable.notification_task, msgContent,
//										"城管通任务提醒", msgContent);
//							}
//							showHs(taskCount);
//						}else
//						{
//							showHs(0);
//						}
//						//我的核查============
//
//						 taskCount= task.getHc();
//						// txtTask.setText(taskCount + "×");
//						if (taskCount > 0)
//						{
//							String msgContent = "您有" + taskCount + "个未核查的任务!";
//							if (!NotificationCreater
//									.isNotificationAvailable(R.drawable.notification_task))
//							{
//								NotificationCreater.createNotification(
//										FrmMain.this, new Intent(FrmMain.this,
//												FrmMyTask.class),
//										R.drawable.notification_task, msgContent,
//										"城管通任务提醒", msgContent);
//							}
//							showHc(taskCount);
//						}else
//						{
//							showHc(0);
//						}
//					}
//				}
			}
			else if (msg.arg1 == HandlerStatus.HANDLE_ERROR)
			{
				Msg.showInfo(FrmMain.this, "无法获取消息提醒数!");
			}
		}
//		else if (msg.what == HandlerStatus.REQUEST_UPLOADCACHECASE)
//		{
//			if (msg.arg1 == HandlerStatus.HANDLE_OK)
//			{
//				checkAndUploadCacheCase();
//				showedNotification = false;
//			}
//			else if (!showedNotification)
//			{
//				// NotificationCreater.createNotification(ApplicationMain.getInstance(),
//				// R.drawable.exe_icon, "与服务器连接已断开",
//				// "城管通", "当前与服务器连接已断开,请新检查配置!");
//				Log.w("Cgt.ConnectServer.Error", "与服务器连接已断开");
//				showedNotification = true;
//			}
//		}
//		else if (msg.what == HandlerStatus.REQUEST_DATASYNC)
//		{
//			if (msg.arg1 == HandlerStatus.HANDLE_OK)
//			{
//				String[] xmlResult = ((ResponseResult<String[]>) msg.obj).getResultObj();
//				if (!StringUtils.isNullOrEmpty(xmlResult[0]))
//				{
//					boolean syncOk = true;
//					CaseTypeConfig typeConfig = new CaseTypeConfig();
//					typeConfig.inputNew(xmlResult[0]);
//					typeConfig.setFileName(CaseTypeConfig.XMLFILENAME);
//					try
//					{
//						typeConfig.write(ApplicationMain.getInstance().getCgtConfig().getTypeConfigEncoding());
//						syncOk = true;
//					}
//					catch (IOException e)
//					{
//						syncOk = false;
//					}
//					if (!StringUtils.isNullOrEmpty(xmlResult[1]) && syncOk)
//					{
//						CaseStatusConfig statusConfig = new CaseStatusConfig();
//						statusConfig.inputNew(xmlResult[1]);
//						statusConfig.setFileName(CaseStatusConfig.XMLFILENAME);
//						try
//						{
//							statusConfig.write();
//							syncOk = true;
//						}
//						catch (IOException e)
//						{
//							syncOk = false;
//						}
//						if (!StringUtils.isNullOrEmpty(xmlResult[2]) && syncOk)
//						{
//							CaseModuleConfig moduleConfig = new CaseModuleConfig();
//							moduleConfig.inputNew(xmlResult[2]);
//							moduleConfig
//									.setFileName(CaseModuleConfig.XMLFILENAME);
//							try
//							{
//								moduleConfig.write();
//								syncOk = true;
//							}
//							catch (IOException e)
//							{
//								syncOk = false;
//							}
//						}
//					}
//					if (syncOk)
//					{
//						getCgtConfig().setDbVersion(
//								getCgtConfig().getDbVersion() + 1);
//						getApplicationMain().setDbHelper(
//								new DbHelper(getApplicationMain(),
//										ConfigLoader.CGTDBS, null,
//										getCgtConfig().getDbVersion()));
////						Msg.showInfo(FrmMain.this, "首次登录数据自动同步成功!");
//					}
//					else
//					{
//						Msg.showInfo(FrmMain.this, "首次登录数据自动同步失败!");
//					}
//				}
//				else
//				{
//					Msg.showInfo(FrmMain.this, "首次登录数据自动同步失败!");
//				}
//			}
//			else if (msg.arg1 == HandlerStatus.HANDLE_ERROR)
//			{
//				Msg.showInfo(FrmMain.this, "首次登录数据自动同步过程中出现错误!");
//			}
//		}
		else if (msg.what == HandlerStatus.REQUEST_CHECKCONFIG)
		{
			if (msg.arg1 == HandlerStatus.HANDLE_OK)
			{
				final CgtConfig config = (CgtConfig) msg.obj;

				if (config.getNowConfigVersion() > getCgtConfig()
						.getNowConfigVersion())
				{

					getCgtConfig().setNowConfigVersion(config.getNowConfigVersion());
					getCgtConfig().setUploadImageLength(config.getUploadImageLength());
					getCgtConfig().setMsgTaskRequestSeparate(config.getMsgTaskRequestSeparate());
					getCgtConfig().setDutyGridLayerIndex(config.getDutyGridLayerIndex());
					getCgtConfig().setPartLayerIndex(config.getPartLayerIndex());
					getCgtConfig().setGridLayerIndex(config.getGridLayerIndex());
					getCgtConfig().setRequestUrl(config.getRequestUrl());
					getCgtConfig().setPictureSubmitUrl(config.getPictureSubmitUrl());
					getCgtConfig().setMapServiceUrl(config.getMapServiceUrl());
					getCgtConfig().setUploadEncoding(config.getUploadEncoding());
					getCgtConfig().setTypeConfigEncoding(config.getTypeConfigEncoding());
					getCgtConfig().setGpsReportTimer(config.getGpsReportTimer());
					getCgtConfig().setGpsReportLength(config.getGpsReportLength());
					getCgtConfig().setPageSize(config.getPageSize());

//					Msg.showInfo(FrmMain.this, "配置信息已更新!");
				}
			}
			else if (msg.arg1 == HandlerStatus.HANDLE_FAIL)
			{
				Msg.showInfo(FrmMain.this, "检查配置更新失败!");
			}
			else
			{
				Msg.showInfo(FrmMain.this, "检查配置更新出错!");
			}
		}
	}


//	public void showMessage(int count)
//	{
//		if (createFlag)
//		{
//			try{
//				ImageTextButton ib=(ImageTextButton)btn_MsgAlert;
//				ImageView mImageView=ib.getmImageView();
//				FrameLayout fr=(FrameLayout)mImageView.getParent();
//				BadgeView bv = (BadgeView)fr.getChildAt(1);
//				if(count>0)
//				{
//				bv.setText(""+count);
//				bv.show();
//				}else
//				{
//					bv.hide();
//				}
//			}catch(Exception e)//当第一次加载,执行下面。
//			{
//
//					ImageTextButton ib=(ImageTextButton)btn_MsgAlert;
//					ImageView mImageView=ib.getmImageView();
//					BadgeView badge = new BadgeView(this, mImageView);
//					badge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
//					if(count>0)
//					{
//
//						// badge.setBackgroundResource(R.drawable.badge_bg);
//						badge.setText(""+count);
//						badge.show();
//					}else
//					{
//					badge.hide();
//					}
//
//			}
//		}
//	}

//	public void showHs(int count)
//	{
//		if (createFlag)
//		{
//			try{
//				ImageTextButton ib=(ImageTextButton)btn_ProblemCheck;
//				ImageView mImageView=ib.getmImageView();
//				FrameLayout fr=(FrameLayout)mImageView.getParent();
//				BadgeView bv = (BadgeView)fr.getChildAt(1);
//				if(count>0)
//				{
//				bv.setText(""+count);
//				bv.show();
//				}else
//				{
//					bv.hide();
//				}
//			}catch(Exception e)//当第一次加载,执行下面。
//			{
//				ImageTextButton ib=(ImageTextButton)btn_ProblemCheck;
//				ImageView mImageView=ib.getmImageView();
//				BadgeView badge = new BadgeView(this, mImageView);
//				 // badge.setBadgePosition(BadgeView.POSITION_CENTER);
//				//badge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
//				if(count>0)
//				{
//
//					// badge.setBackgroundResource(R.drawable.badge_bg);
//					badge.setText(""+count);
//					badge.show();
//				}else
//				{
//				badge.hide();
//				}
//			}
//		}
//	}


//	public void showHc(int count)
//	{
//		if (createFlag)
//		{
//			try{
//				ImageTextButton ib=(ImageTextButton)btn_ProblemReCheck;
//				ImageView mImageView=ib.getmImageView();
//				FrameLayout fr=(FrameLayout)mImageView.getParent();
//				BadgeView bv = (BadgeView)fr.getChildAt(1);
//				if(count>0)
//				{
//				bv.setText(""+count);
//				bv.show();
//				}else
//				{
//					bv.hide();
//				}
//			}catch(Exception e)//当第一次加载,执行下面。
//			{
//				ImageTextButton ib=(ImageTextButton)btn_ProblemReCheck;
//				ImageView mImageView=ib.getmImageView();
//				BadgeView badge = new BadgeView(this, mImageView);
//				//badge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
//				if(count>0)
//				{
//
//					// badge.setBackgroundResource(R.drawable.badge_bg);
//					badge.setText(""+count);
//					badge.show();
//				}else
//				{
//				badge.hide();
//				}
//			}
//		}
//	}

//	public void showDeal(int count)
//	{
//		if (createFlag)
//		{
//			try{
//				ImageTextButton ib=(ImageTextButton)btn_MyTask;
//				ImageView mImageView=ib.getmImageView();
//				FrameLayout fr=(FrameLayout)mImageView.getParent();
//				BadgeView bv = (BadgeView)fr.getChildAt(1);
//				if(count>0)
//				{
//					bv.setText(""+count);
//					bv.show();
//				}else
//				{
//					bv.hide();
//				}
//			}catch(Exception e)//当第一次加载,执行下面。
//			{
//				ImageTextButton ib=(ImageTextButton)btn_MyTask;
//				ImageView mImageView=ib.getmImageView();
//				BadgeView badge = new BadgeView(this, mImageView);
//				//badge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
//				if(count>0)
//				{
//
//					// badge.setBackgroundResource(R.drawable.badge_bg);
//					badge.setText(""+count);
//					badge.show();
//				}else
//				{
//					badge.hide();
//				}
//			}
//
//
//		}
//
//	}


	@Override
	protected void onCancelProgress(DialogInterface arg0)
	{
	}

	/**
	 * 通过巡查员所在责任网格编号获取责任网格的点集
	 */
	private void getBgPoints()
	{
		final BaseThread baseThread = new BaseThread(baseHandler)
		{
			@Override
			public void runThread()
			{
				GisUtil gisUtil = new GisUtil()
				{
					@Override
					public void queryFeature(String url) throws IOException,
							JSONException
					{
						// TODO 获取责任网格点集
//						StringBuffer queryString = new StringBuffer();
//						queryString.append("{\"queryMode\":\"SqlQuery\",");
//						queryString.append("\"queryParameters\":");
//						queryString.append("{\"queryParams\":[{\"name\":\"");
//						queryString.append("责任网格@yanan");
//						queryString.append("\",\"attributeFilter\":\"WGCODE='");
//						queryString.append(getApplicationMain().getUserModel().getBgCode());
//						queryString
//								.append("'\",\"fields\":[\"WGCODE\"]}],\"expectCount\":1,\"queryOption\":\"ATTRIBUTEANDGEOMETRY\"}}");
//						String postString = queryString.toString();
//
//						String resultString = HttpRequestTools.postReturnString(url, postString, null, 0).trim();
//
//						JSONObject result = new JSONObject(resultString);
//						if (result.getBoolean("succeed")) {
//							String resourceLocation = result.getString("newResourceLocation");
//							String featureJsonStr = HttpRequestTools.getReturnString(resourceLocation, null, 0);
//							JSONObject jsonObject = new JSONObject(featureJsonStr);
//							if (jsonObject.has("currentCount") && jsonObject.getInt("currentCount") > 0) {
//								JSONArray recordsets = jsonObject.getJSONArray("recordsets");
//								JSONObject recordset = (JSONObject)
//										recordsets.get(0);
//								JSONArray features = recordset.getJSONArray("features");
//								JSONObject feature = (JSONObject) features.get(0);
//								JSONObject geometry = feature.getJSONObject("geometry");
//								JSONArray points = geometry.getJSONArray("points");
//								PointD[] pointArr = new PointD[points.length()];
//								for (int i = 0; i < points.length(); i++) {
//									JSONObject point = (JSONObject) points.get(i);
//									PointD p = new PointD(point.getDouble("x"),
//											point.getDouble("y"));
//									pointArr[i] = p;
//								}
//								getApplicationMain().getUserModel().setBgPoints(pointArr);
//							}
//						}
					}
				};
				int requestCount = 0;
				while (this.getIsThreadGoing())
				{
					try
					{
						gisUtil.queryFeature(getCgtConfig().getMapServiceUrl()
								+ "/queryResults.json");
						break;
					}
					catch (IOException e)
					{
						try
						{
							sleep(180 * 1000);
						}
						catch (InterruptedException e1)
						{
							break;
						}
						e.printStackTrace();
					}
					catch (JSONException e)
					{
						Log.w("责任网格矢量查询", "查询责任网格矢量时无法格式化JSON字符串");
						e.printStackTrace();
						break;
					}
					requestCount++;
					if (requestCount >= 5)
					{
						break;
					}
				}
			}
		};
		baseThread.start();
	}
	/**
	 * 轮循获取消息及任务数
	 */
	private void getMsgAndTask()
	{
		msgTaskLoopThread = new BaseThread(baseHandler)
		{
			@Override
			public void runThread()
			{
				while(true)
				{
					if (msgTaskLoopThread.getIsThreadGoing())
					{
						reportGpsPosition1();

						boolean canUploadCacheCase = true;

						Message msgUploadCache = msgTaskLoopThread.obtainMessage();
						if (msgUploadCache != null)
						{
							msgUploadCache.what = HandlerStatus.REQUEST_UPLOADCACHECASE;
							if (canUploadCacheCase)
							{
								msgUploadCache.arg1 = HandlerStatus.HANDLE_OK;
							}
							else
							{
								msgUploadCache.arg1 = HandlerStatus.HANDLE_ERROR;
							}
							msgTaskLoopThread.sendMessage(msgUploadCache);
						}
					}
					try
					{
						Thread.sleep(120 * 1000);
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
						break;
					}
				}
			}
		};
		msgTaskLoopThread.start();
	}

	/**
	 * 检测是否有缓存的案卷并上传
	 */
//	private void checkAndUploadCacheCase()
//	{
//
//		getDbHelper().exeSql(new DbExecuteHelper()
//		{
//			@Override
//			public void exeSqlMethod(SQLiteDatabase db)
//			{
//				List<CaseModel> cacheCaseList = new ArrayList<CaseModel>();
//				Cursor query = db.rawQuery(
//						MessageFormat
//								.format("select rowId,id,caseId,caseTypeId,caseTypeName,caseLClassId,caseLClassName,"
//										+ "caseSClassId,caseSClassName,caseModuleId,caseModuleName,caseAddress,"
//										+ "caseSituation,caseLongitude,caseLatitude,casePartNum,caseGrid,"
//										+ "dispatchRequire,dealResult,endTime,startTime,caseStatusId,caseStatusName,"
//										+ "leaveTime,jbpmid,startTimeDate,startTimeTime,returnCheckMemo,dept1,dept2,dept3 from {0}",
//										DbHelper.TABLE_CASE), null);
//				if (query.getCount() > 0)
//				{
//					while (query.moveToNext())
//					{
//						CaseModel caseModel = new CaseModel(query.getString(0),
//								query.getString(1), query.getString(2), query
//										.getString(3), query.getString(4),
//								query.getString(5), query.getString(6), query
//										.getString(7), query.getString(8),
//								query.getString(9), query.getString(10), query
//										.getString(11), query.getString(12),
//								query.getString(13), query.getString(14), query
//										.getString(15), query.getString(16),
//								query.getString(17), query.getString(18), query
//										.getString(19), query.getString(20),
//								query.getString(21), query.getString(22), query
//										.getString(23), query.getString(24),
//								query.getString(25), query.getString(26), query
//										.getString(27), query.getString(28),
//								query.getString(29), query.getString(30));
//
//						cacheCaseList.add(caseModel);
//					}
//				}
//				query.close();
//				if (cacheCaseList.size() > 0)
//				{
//					for (CaseModel caseModel : cacheCaseList)
//					{
//						submitCase(caseModel);
//					}
//				}
//			}
//		});
//	}

//	private void submitCase(final CaseModel toSubmitCase)
//	{
//		BaseThread thread = new BaseThread(baseHandler)
//		{
//			@Override
//			public void runThread()
//			{
//				try
//				{
//					ResponseResult<String[]> result = Request.getRequest()
//							.inputNewCase(
//									ApplicationMain.getInstance()
//											.getUserModel().getBgAdminId(),
//									toSubmitCase.getCaseTypeId(),
//									toSubmitCase.getCaseLClassId(),
//									toSubmitCase.getCaseSClassId(),
//									toSubmitCase.getCaseModuleId(),
//									toSubmitCase.getCaseAddress(),
//									toSubmitCase.getCaseSituation(),
//									toSubmitCase.getCaseLongitude(),
//									toSubmitCase.getCaseLatitude(),
//									toSubmitCase.getCasePartNum(),
//									toSubmitCase.getCaseGrid(),
//									StringUtils.isNullOrEmpty(toSubmitCase
//											.getDept3()) ? toSubmitCase
//											.getDept2() : toSubmitCase
//											.getDept3(),"0",toSubmitCase.getDq(),toSubmitCase.getJd(),toSubmitCase.getSq());
//					if (result.isSuccess())
//					{
//						getDbHelper().exeSql(new DbExecuteHelper()
//						{
//							@Override
//							public void exeSqlMethod(SQLiteDatabase db)
//							{
//								db.delete(
//										DbHelper.TABLE_CASE,
//										" rowid= ?",
//										new String[] { toSubmitCase.getRowId() });
//							}
//						});
//						String[] resultIds = result.getResultObj();
//						if (resultIds != null)
//						{
//							String pictureId = resultIds[0].trim();
//							String eventId = resultIds[1].trim();
//							List<String> imagePath = Request.getRequest()
//									.getCacheImage(toSubmitCase.getRowId());
//							String audioPath = Request.getRequest()
//									.getCacheAudio(toSubmitCase.getRowId());
//
//							if (imagePath.size() > 0)
//							{
//								for (int i = 0; i < imagePath.size(); i++)
//								{
//									Request.getRequest().submitImage(
//											imagePath.get(i), pictureId, i,
//											eventId);
//								}
//							}
//							if (new File(audioPath).exists())
//							{
//								Request.getRequest().submitAudio(audioPath,
//										pictureId, eventId);
//							}
//							Request.getRequest().saveImageCache(null, eventId,
//									toSubmitCase.getRowId());
//						}
//					}
//				}
//				catch (Exception e)
//				{
//					e.printStackTrace();
//				}
//				this.interrupt();
//			}
//		};
//		thread.start();
//		threadList.add(thread);
//	}

	/**
	 * @param needShowLogin
	 *            关闭后是否需要再打开登录窗口
	 */
	public void finishActivity(boolean needShowLogin)
	{
		if (checkCanFinishActivity())
		{
			FrmMain.this.finish();
			if (needShowLogin)
			{
				Intent intent = new Intent(FrmMain.this, FrmLogin.class);
				startActivity(intent);
			}
		}
		else
		{
			Msg.showInfo(this, "正在上报案卷中,暂时无法退出程序!");
		}
	}

	private boolean checkCanFinishActivity()
	{
		boolean canFinish = true;
		for (int i = threadList.size() - 1; i >= 0; i--)
		{
			BaseThread thread = threadList.get(i);
			if (thread != null && thread.getIsThreadGoing())
			{
				canFinish = false;
			}
			else
			{
				threadList.remove(i);
			}
		}
		return canFinish;
	}

	/**
	 * 数据同步,大类小类、街道等缓存数据的同步
	 */
//	private void autoUpdateCacheData()
//	{
//		BaseThread threadAutoUpdate = new BaseThread(baseHandler)
//		{
//			@Override
//			public void runThread()
//			{
//				Message msg = this.obtainMessage();
//				msg.what = HandlerStatus.REQUEST_DATASYNC;
//				ResponseResult<String[]> syncResult = null;
//				try
//				{
//					syncResult = Request.getRequest().startDataSync(null);
//					if (syncResult.isSuccess())
//					{
//						msg.arg1 = HandlerStatus.HANDLE_OK;
//					}
//					else if (syncResult.isHadError())
//					{
//						msg.arg1 = HandlerStatus.HANDLE_ERROR;
//					}
//					else
//					{
//						msg.arg1 = HandlerStatus.HANDLE_FAIL;
//					}
//					msg.obj = syncResult;
//				}
//				catch (Exception e)
//				{
//					msg.arg1 = HandlerStatus.HANDLE_ERROR;
//				}
//				this.sendMessage(msg);
//			}
//		};
//		threadAutoUpdate.start();
//	}

//	private void autoCheckConfig()
//	{
//		BaseThread updateThread = new BaseThread(baseHandler)
//		{
//
//			@Override
//			public void runThread()
//			{
//				Message msg = this.obtainMessage();
//				msg.what = HandlerStatus.REQUEST_CHECKCONFIG;
//				try
//				{
//					ResponseResult<CgtConfig> configResult = Request
//							.getRequest().checkAndGetNewConfig(
//									getCgtConfig().getNowConfigVersion());
//					if (configResult.isSuccess())
//					{
//						msg.arg1 = HandlerStatus.HANDLE_OK;
//					}
//					else if (configResult.isHadError())
//					{
//						msg.arg1 = HandlerStatus.HANDLE_ERROR;
//					}
//					else
//					{
//						msg.arg1 = HandlerStatus.HANDLE_FAIL;
//					}
//					msg.obj = configResult.getResultObj();
//				}
//				catch (Exception e)
//				{
//					msg.arg1 = HandlerStatus.HANDLE_ERROR;
//				}
//				this.sendMessage(msg);
//
//			}
//		};
//		updateThread.start();
//	}

	// ==================修改用户图片的方法======================
	// 调用系统方法裁剪图片
	private void startPhotoZoom(Uri uri, int size)
	{
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// crop为true是设置在开启的intent中设置显示的view可以剪裁
		intent.putExtra("crop", "true");

		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);

		// outputX,outputY 是剪裁图片的宽高
		intent.putExtra("outputX", size);
		intent.putExtra("outputY", size);
		intent.putExtra("return-data", true);

		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	// 将进行剪裁后的图片显示到UI界面上
	private void setPicToView(Intent picdata)
	{
		Bundle bundle = picdata.getExtras();
		if (bundle != null)
		{
			Bitmap photo = bundle.getParcelable("data");
			photo = getRoundedCornerBitmap(photo);
			Drawable drawable = new BitmapDrawable(photo);
			imguser.setImageDrawable(drawable);
			byte[] bytes = Bitmap2Bytes(photo);
			getFileFromBytes(bytes, FILEPATH);
		}
	}

	/**
	 * 将bitmap转换成byte[]
	 */
	public static byte[] Bitmap2Bytes(Bitmap bm)
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	/**
	 * 将byte写入文件
	 */
	public File getFileFromBytes(byte[] b, String outputFile)
	{
		BufferedOutputStream stream = null;
		File file = null;
		try
		{
			if (FileUtils.isFileExists(outputFile))
			{
				FileUtils.deleteFile(FILEPATH);
			}
			file = new File(outputFile);
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (stream != null)
			{
				try
				{
					stream.close();
				}
				catch (IOException e1)
				{
					e1.printStackTrace();
				}
			}
		}
		return file;
	}

	// 使用系统当前日期加以调整作为图片的名称
	private String getPhotoFileName()
	{
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".jpg";
	}

//	GpsStatus.Listener gpsS = new GpsStatus.Listener() {
//		@Override
//		public void onGpsStatusChanged(int event) {
//		gpscount = 0;
//		// TODO Auto-generated method stub
//		if(event==GpsStatus.GPS_EVENT_FIRST_FIX){
//		           //第一次定位
//		       }else if(event==GpsStatus.GPS_EVENT_SATELLITE_STATUS){
//		           //卫星状态改变
//		           GpsStatus gpsStauts= GpsManager.getLocationManager().getGpsStatus(null); // 取当前状态
//		           int maxSatellites = gpsStauts.getMaxSatellites(); //获取卫星颗数的默认最大值
//
//		           Iterator<GpsSatellite> it = gpsStauts.getSatellites().iterator();//创建一个迭代器保存所有卫星
//		           while (it.hasNext() && gpscount <= maxSatellites) {
//		               GpsSatellite s = it.next();
//		               //可见卫星数量
//		               if(s.usedInFix()){
//		               //已定位卫星数量
//		               gpscount++;
//		               }
//		           }
//		           main_headId.setText(user.getUserName()+user.getUserId()+"GPS卫星数量:"+gpscount+"颗");
//
//		       }else if(event==GpsStatus.GPS_EVENT_STARTED){
//		           //定位启动
//		       }else if(event==GpsStatus.GPS_EVENT_STOPPED){
//		           //定位结束
//		       }
//		}
//		};

	// 提示对话框方法
	private void showDialog()
	{
		new AlertDialog.Builder(this)
				.setTitle("头像设置")
				.setPositiveButton("拍照", new DialogInterface.OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
						// 调用系统的拍照功能
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);
						// 指定调用相机拍照后图片的储存路径
						intent.putExtra(MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(tempFile));
						startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
					}
				})
				.setNegativeButton("相册", new DialogInterface.OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
						Intent intent = new Intent(Intent.ACTION_PICK, null);
						intent.setDataAndType(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
								"image/*");
						startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
					}
				}).show();
	}

	/**
	 * 获取圆形头像
	 */
	public Bitmap getRoundedCornerBitmap(Bitmap bitmap)
	{
		Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(outBitmap);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPX = bitmap.getWidth() / 2;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPX, roundPX, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return outBitmap;
	}
	// =======================================================

//	 /**
//     * onSaveInstanceState和onRestoreInstanceState一般都是配合着使用的
//     * 方法只有在程序以外退出或Activity异常终止的时才会被调用,用于保存数据
//     * @param outState
//     */
//    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
//        // 键值对 key value
//        outState.putString("save_name",user.getUserName());
//        outState.putString("save_adminid",user.getBgAdminId());
//        outState.putString("save_userid",user.getUserId());
//        outState.putString("save_bgcode",user.getBgCode());
//    }


//    /**
//     * onRestoreInstanceState
//     * 用于恢复在以外发生之前保存的数据
//     * @param savedInstanceState
//     */
//    @Override
//    protected void onRestoreInstanceState(Bundle savedInstanceState) {
//        super.onRestoreInstanceState(savedInstanceState);
//        // 获取 key 所对应的 value
//        String save_name = savedInstanceState.getString("save_name");
//        String save_adminid = savedInstanceState.getString("save_adminid");
//        String save_userid = savedInstanceState.getString("save_userid");
//        String save_bgcode = savedInstanceState.getString("save_bgcode");
//        user=new UserModel();
//        user.setUserName(save_name);
//        user.setBgAdminId(save_adminid);
//        user.setUserId(save_userid);
//        user.setBgCode(save_bgcode);
//        ApplicationMain.getInstance().setUserModel(user);
//
//    }


}