public class UserManageActivity extends BaseActivity implements OnClickListener {

	/** The iv TopBar leftBtn. */
	private ImageView ivBack;

	/** The et User name. */
	private TextView tvName;

	/** The btn to update pass page. */
	private Button btnChange;

	/** The btn logout . */
	private Button btnLogout;

	/** The dialog. */
	private Dialog dialog;

	/* (non-Javadoc)
	 * @see com.gizwits.framework.activity.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_manage);
		initViews();
		initEvents();

	}

	/**
	 * Inits the events.
	 */
	private void initEvents() {
		btnChange.setOnClickListener(this);
		btnLogout.setOnClickListener(this);
		ivBack.setOnClickListener(this);

	}

	/**
	 * Inits the views.
	 */
	private void initViews() {
		ivBack = (ImageView) findViewById(R.id.ivBack);
		tvName = (TextView) findViewById(R.id.tvName);
		btnChange = (Button) findViewById(R.id.btnChange);
		btnLogout = (Button) findViewById(R.id.btnLogout);
		tvName.setText(setmanager.getUserName());
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ivBack:
			onBackPressed();
			break;
		case R.id.btnChange:
			IntentUtils.getInstance().startActivity(UserManageActivity.this,
					ChangePswActivity.class);
			break;
		case R.id.btnLogout:
			if (dialog == null) {
				dialog = DialogManager.getLogoutDialog(UserManageActivity.this,
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								setmanager.setToken("");
								DialogManager.dismissDialog(
										UserManageActivity.this, dialog);
								ToastUtils.showShort(UserManageActivity.this,
										"注销成功");
								IntentUtils.getInstance().startActivity(
										UserManageActivity.this,
										LoginActivity.class);
								finish();
							}
						});
			}

			DialogManager.showDialog(UserManageActivity.this, dialog);
			break;
		}

	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		finish();
	}

} public class DeviceListActivity extends BaseActivity implements
		OnClickListener, OnItemClickListener {

	/** The Constant TAG. */
	private static final String TAG = "DeviceListActivity";

	/**
	 * The iv TopBar leftBtn.
	 */
	private ImageView ivLogout;

	/** The iv add. */
	private ImageView ivAdd;

	/** The tv init date. */
	private RefreshableListView lvDevices;

	/** The device list adapter. */
	private DeviceListAdapter deviceListAdapter;

	/** The progress dialog. */
	private ProgressDialog progressDialog;

	/** The dialog. */
	private Dialog dialog;
	
	/** 登陆设备超时时间 */
	private int LoginDeviceTimeOut = 60000;

	/** 网络状态广播接受器. */
	private ConnecteChangeBroadcast mChangeBroadcast = new ConnecteChangeBroadcast();

	/**
	 * The boolean isExit.
	 */
	private boolean isExit = false;

	/**
	 * ClassName: Enum handler_key. <br/>
	 * <br/>
	 * date: 2014-11-26 17:51:10 <br/>
	 * 
	 * @author Lien
	 */
	private enum handler_key {

		/** The login start. */
		LOGIN_START,

		/**
		 * The login success.
		 */
		LOGIN_SUCCESS,

		/**
		 * The login fail.
		 */
		LOGIN_FAIL,

		/**
		 * The login timeout.
		 */
		LOGIN_TIMEOUT,

		/** The found. */
		FOUND,

		/**
		 * Exit the app.
		 */
		EXIT,

	}

	/** The handler. */
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			handler_key key = handler_key.values()[msg.what];
			switch (key) {
			case FOUND:
				lvDevices.completeRefreshing();
				break;

			case LOGIN_SUCCESS:
				DialogManager.dismissDialog(DeviceListActivity.this, progressDialog);
				IntentUtils.getInstance().startActivity(
						DeviceListActivity.this, MainControlActivity.class);
				break;

			case LOGIN_FAIL:
				DialogManager.dismissDialog(DeviceListActivity.this, progressDialog);
				ToastUtils.showShort(DeviceListActivity.this, "连接失败");
				break;
			case LOGIN_TIMEOUT:
				DialogManager.dismissDialog(DeviceListActivity.this, progressDialog);
				ToastUtils.showShort(DeviceListActivity.this, "连接失败");
				break;
			case EXIT:
				isExit = false;
				break;
			}
			deviceListAdapter.changeDatas(deviceslist);
		}

	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.gizwits.framework.activity.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_devicelist);
		initViews();
		initEvents();
		if (getIntent() != null) {
			if (getIntent().getBooleanExtra("autoLogin", false)) {
				mCenter.cLogin(setmanager.getUserName(),
						setmanager.getPassword());
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.gizwits.framework.activity.BaseActivity#onResume()
	 */
	@Override
	public void onResume() {
		super.onResume();
		deviceListAdapter.changeDatas(new ArrayList<XPGWifiDevice>());
		
		if (getIntent().getBooleanExtra("isbind", false)) {

			mCenter.cBindDevice(setmanager.getUid(), setmanager.getToken(),
					getIntent().getStringExtra("did"), getIntent()
							.getStringExtra("passcode"), "");
		} else {
			getList();
		}

		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(mChangeBroadcast, filter);

	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(mChangeBroadcast);
	}

	/**
	 * Inits the views.
	 */
	private void initViews() {
		ivLogout = (ImageView) findViewById(R.id.ivLogout);
		ivAdd = (ImageView) findViewById(R.id.ivAdd);
		lvDevices = (RefreshableListView) findViewById(R.id.lvDevices);

		// deviceList = new ArrayList<XPGWifiDevice>();
		deviceListAdapter = new DeviceListAdapter(this, deviceslist);
		lvDevices.setAdapter(deviceListAdapter);
		lvDevices.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh(RefreshableListView listView) {
				getList();

			}
		});
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("连接中，请稍候。");
		progressDialog.setCancelable(false);
	}

	/**
	 * Inits the events.
	 */
	private void initEvents() {
		ivLogout.setOnClickListener(this);
		ivAdd.setOnClickListener(this);
		lvDevices.setOnItemClickListener(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ivAdd:
			IntentUtils.getInstance().startActivity(DeviceListActivity.this,
					SearchDeviceActivity.class);
			break;
		case R.id.ivLogout:
			if (dialog == null) {
				dialog = DialogManager.getLogoutDialog(DeviceListActivity.this,
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								setmanager.setToken("");
								setmanager.setUserName("");
								setmanager.setPassword("");
								setmanager.setUid("");
								
								DialogManager.dismissDialog(
										DeviceListActivity.this, dialog);
								ToastUtils.showShort(DeviceListActivity.this,
										"注销成功");
								IntentUtils.getInstance().startActivity(
										DeviceListActivity.this,
										LoginActivity.class);
								finish();
							}
						});
			}

			DialogManager.showDialog(DeviceListActivity.this, dialog);
			break;
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget
	 * .AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		XPGWifiDevice tempDevice = deviceListAdapter
				.getDeviceByPosition(position);
		if (tempDevice == null) {
			return;
		}
		if (tempDevice.isLAN()) {
			if (tempDevice.isBind(setmanager.getUid())) {
				// TODO 登陆设备
				Log.i(TAG,
						"本地登陆设备:mac=" + tempDevice.getPasscode() + ";ip="
								+ tempDevice.getIPAddress() + ";did="
								+ tempDevice.getDid() + ";passcode="
								+ tempDevice.getPasscode());
				loginDevice(tempDevice);
			} else {
				// TODO 未设备
				Log.i(TAG,
						"绑定设备:mac=" + tempDevice.getMacAddress() + ";ip="
								+ tempDevice.getIPAddress() + ";did="
								+ tempDevice.getDid() + ";passcode="
								+ tempDevice.getPasscode());
				Intent intent = new Intent(DeviceListActivity.this,
						BindingDeviceActivity.class);
				intent.putExtra("mac", tempDevice.getMacAddress());
				intent.putExtra("did", tempDevice.getDid());
				startActivity(intent);
			}
		} else {
			if (!tempDevice.isOnline()) {
				// TODO 离线
				Log.i(TAG,
						"离线设备:mac=" + tempDevice.getPasscode() + ";ip="
								+ tempDevice.getIPAddress() + ";did="
								+ tempDevice.getDid() + ";passcode="
								+ tempDevice.getPasscode());
			} else {
				// TODO 登陆设备
				Log.i(TAG,
						"远程登陆设备:mac=" + tempDevice.getPasscode() + ";ip="
								+ tempDevice.getIPAddress() + ";did="
								+ tempDevice.getDid() + ";passcode="
								+ tempDevice.getPasscode());
				loginDevice(tempDevice);
			}
		}

	}

	/**
	 * 登陆设备
	 * 
	 * @param xpgWifiDevice
	 *            the xpg wifi device
	 */
	private void loginDevice(XPGWifiDevice xpgWifiDevice) {
		DialogManager.showDialog(DeviceListActivity.this, progressDialog);
		mXpgWifiDevice = xpgWifiDevice;
		mXpgWifiDevice.setListener(deviceListener);
		if(mXpgWifiDevice.isConnected()){
			handler.sendEmptyMessage(handler_key.LOGIN_SUCCESS.ordinal());
		}else{
			handler.sendEmptyMessageDelayed(handler_key.LOGIN_TIMEOUT.ordinal(), LoginDeviceTimeOut);
			mXpgWifiDevice.login(setmanager.getUid(), setmanager.getToken());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.gizwits.framework.activity.BaseActivity#didLogin(com.xtremeprog.
	 * xpgconnect.XPGWifiDevice, int)
	 */
	@Override
	protected void didLogin(XPGWifiDevice device, int result) {
		handler.removeMessages(handler_key.LOGIN_TIMEOUT.ordinal());
		if (result == 0) {
			mXpgWifiDevice = device;
			handler.sendEmptyMessage(handler_key.LOGIN_SUCCESS.ordinal());
		} else {
			handler.sendEmptyMessage(handler_key.LOGIN_FAIL.ordinal());
		}

	}

	/**
	 * 处理获取设备列表动作
	 * 
	 * @return the list
	 */
	private void getList() {
		String uid = setmanager.getUid();
		String token = setmanager.getToken();
		mCenter.cGetBoundDevices(uid, token);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.gizwits.framework.activity.BaseActivity#didDiscovered(int,
	 * java.util.List)
	 */
	@Override
	protected void didDiscovered(int error, List<XPGWifiDevice> deviceList) {
		deviceslist = deviceList;
		handler.sendEmptyMessage(handler_key.FOUND.ordinal());

	}

	@Override
	protected void didDisconnected(XPGWifiDevice device) {
		if (mXpgWifiDevice.getDid().equals(device.getDid())) {
			handler.sendEmptyMessage(handler_key.LOGIN_FAIL.ordinal());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.gizwits.framework.activity.BaseActivity#didUserLogin(int,
	 * java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	protected void didUserLogin(int error, String errorMessage, String uid,
			String token) {
		if (!uid.isEmpty() && !token.isEmpty()) {// 登陆成功
			setmanager.setUid(uid);
			setmanager.setToken(token);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		exit();
	}

	/**
	 * 广播监听器，监听wifi连上的广播.
	 * 
	 * @author Lien
	 */
	public class ConnecteChangeBroadcast extends BroadcastReceiver {

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * android.content.BroadcastReceiver#onReceive(android.content.Context,
		 * android.content.Intent)
		 */
		@Override
		public void onReceive(Context context, Intent intent) {
			if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent
					.getAction())) {
				getList();
			}
		}
	}

} public class DeviceManageListActivity extends BaseActivity implements OnClickListener {
    /**
     * The iv TopBar leftBtn.
     */
    private ImageView ivBack;

    /** The tv init date. */
    private ListView lvDevices;

    /** The iv add. */
    private ImageView ivAdd;

    /** The Device device list. */
    private List<XPGWifiDevice> devices;

    /** The m adapter. */
    ManageListAdapter mAdapter;

    /* (non-Javadoc)
     * @see com.gizwits.framework.activity.BaseActivity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_device_list);

        initViews();
        initEvents();
    }

    /**
     * Inits the events.
     */
    private void initEvents() {
        lvDevices.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                XPGWifiDevice device = bindlist.get(position);
                    Intent intent = new Intent(DeviceManageListActivity.this,
                            DeviceManageDetailActivity.class);
                    intent.putExtra("mac", device.getMacAddress());
                    intent.putExtra("did", device.getDid());
                    startActivity(intent);
            }
        });
        ivBack.setOnClickListener(this);
        ivAdd.setOnClickListener(this);
    }

    /**
     * Inits the views.
     */
    private void initViews() {
        ivAdd = (ImageView) findViewById(R.id.ivAdd);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        lvDevices = (ListView) findViewById(R.id.lvDevices);
        mAdapter = new ManageListAdapter(DeviceManageListActivity.this,
                bindlist);
        lvDevices.setAdapter(mAdapter);

    }
    
    

    /* (non-Javadoc)
     * @see android.app.Activity#onBackPressed()
     */
    @Override
	public void onResume() {
		super.onResume();
		initBindList();
		mAdapter.notifyDataSetChanged();
	}

	@Override
    public void onBackPressed() {
		boolean isNoOnLineDevice = true;
		for (XPGWifiDevice xpgDevice : bindlist) {
			if (xpgDevice.isOnline())
				isNoOnLineDevice = false;
		}

		if (isNoOnLineDevice) {
			IntentUtils.getInstance().startActivity(DeviceManageListActivity.this,DeviceListActivity.class);
		} else {
			finish();
		}
    }

    /* (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                onBackPressed();
                break;
            case R.id.ivAdd:
                IntentUtils.getInstance().startActivity(DeviceManageListActivity.this,
                        SearchDeviceActivity.class);
                break;
        }
    }
} public class AboutActivity extends BaseActivity {
	
	/** The iv back. */
	private ImageView ivBack;

	/** The iv about. */
	private ImageView ivAbout;

	/** The sv About. */
	private ScrollView svAbout;

	/* (non-Javadoc)
	 * @see com.gizwits.framework.activity.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_about);
		initViews();
	}

	/**
	 * Inits the views.
	 */
	private void initViews() {
		svAbout = (ScrollView) findViewById(R.id.svAbout);
		ivAbout = (ImageView) findViewById(R.id.ivAbout);
		ivBack = (ImageView) findViewById(R.id.ivBack);
		ivBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();

			}
		});
		
		Bitmap mBitmap = BitmapFactory
				.decodeResource(getResources(), R.drawable.about);
		ivAbout.setImageBitmap(mBitmap);
		
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		float width = metric.widthPixels;
		if (width < mBitmap.getWidth()) {
			float mHight = 0;
			float mWidth = 0;
			float scal = 0;
			
			mWidth = width;
			scal = width / mBitmap.getWidth();
			mHight =  scal * mBitmap.getHeight();
			svAbout.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
					(int)mWidth, (int)mHight));
		}
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		finish();
	}

} public class HelpActivity extends BaseActivity implements OnClickListener {

	/** The iv TopBar leftBtn. */
	private ImageView ivBack;

	/** The btn AppHelp. */
	private Button AppHelp;

	/** The btn DeviceHelp. */
	private Button DeviceHelp;

	/* (non-Javadoc)
	 * @see com.gizwits.framework.activity.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_help);
		initViews();
		initEvents();
	}

	/**
	 * Inits the events.
	 */
	private void initEvents() {
		ivBack.setOnClickListener(this);
		AppHelp.setOnClickListener(this);
		DeviceHelp.setOnClickListener(this);

	}

	/**
	 * Inits the views.
	 */
	private void initViews() {
		ivBack = (ImageView) findViewById(R.id.ivBack);
		AppHelp = (Button) findViewById(R.id.AppHelp);
		DeviceHelp = (Button) findViewById(R.id.DeviceHelp);

	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ivBack:
			onBackPressed();
			break;

		default:
			break;
		}

	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		finish();
	}

} public class MenuDeviceAdapter extends BaseAdapter {

	/** The inflater. */
	private LayoutInflater inflater;

	/** The choosed pos. */
	private int choosedPos = 0;

	/** The ctx. */
	private Context ctx;

	/** The wifidevicelist. */
	private List<XPGWifiDevice> devicelist ;

	/**
	 * Gets the choosed pos.
	 * 
	 * @return the choosed pos
	 */
	public int getChoosedPos() {
		return choosedPos;
	}

	/**
	 * Sets the choosed pos.
	 * 
	 * @param choosedPos
	 *            the new choosed pos
	 */
	public void setChoosedPos(int choosedPos) {
		this.choosedPos = choosedPos;
		notifyDataSetChanged();
	}

	/**
	 * Instantiates a new device adapter.
	 * 
	 * @param context
	 *            the context
	 * @param objects
	 *            the objects
	 */
	public MenuDeviceAdapter(Context context, List<XPGWifiDevice> objects) {
		ctx = context;
		inflater = LayoutInflater.from(context);
		devicelist=objects;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.ArrayAdapter#getView(int, android.view.View,
	 * android.view.ViewGroup)
	 */
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		int px = DensityUtil.dip2px(ctx, getCount() * 50);
		parent.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
				android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, px));

		ViewHolder holder = null;
		XPGWifiDevice device = getItem(position);
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.slibbar_item, null);
			holder = new ViewHolder();
			holder.device_checked_tv = (ImageView) convertView
					.findViewById(R.id.device_checked_tv);
			holder.deviceName_tv = (TextView) convertView
					.findViewById(R.id.deviceName_tv);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		String name="";
		if (StringUtils.isEmpty(device.getRemark())) {
			String macAddress = device.getMacAddress();
			int size = macAddress.length();
			name=device.getProductName()
					+ macAddress.substring(size - 4, size);
		} else {
			name=device.getRemark();
		}
		name=StringUtils.getStrFomat(name, Configs.DEVICE_NAME_KEEP_LENGTH, true);
		holder.deviceName_tv.setText(name);

		if (getChoosedPos() == position) {
			holder.deviceName_tv.setSelected(true);
			holder.device_checked_tv.setVisibility(View.VISIBLE);
			;
		} else {
			holder.deviceName_tv.setSelected(false);
			holder.device_checked_tv.setVisibility(View.INVISIBLE);
			;
		}

		if (device.isOnline())
			holder.deviceName_tv.setTextColor(ctx.getResources().getColor(
					R.color.text_blue));
		else
			holder.deviceName_tv.setTextColor(ctx.getResources().getColor(
					R.color.text_gray));

		return convertView;

	}

	/**
	 * 
	 * ClassName: Class ViewHolder. <br/>
	 * <br/>
	 * date: 2015-1-27 14:44:48 <br/>
	 * 
	 * @author Lien
	 */
	private static class ViewHolder {

		/** The device_checked_tv. */
		ImageView device_checked_tv;

		/** The device name_tv. */
		TextView deviceName_tv;
	}

	@Override
	public int getCount() {
		return devicelist.size();
	}

	@Override
	public XPGWifiDevice getItem(int position) {
		return devicelist.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}
} public class JsonKeys {

	/** 产品名. */
	public final static String PRODUCT_NAME = "机智云插座";

	/** 实体字段名，代表对应的项目. */
	public final static String KEY_ACTION = "entity0";

	/** 开关. */
	public final static String ON_OFF = "OnOff";

	/** 每周重复. */
	public final static String WEEK_REPEAT = "Week_Repeat";

	/** 定时开机. */
	public final static String TIME_ON_MINUTE = "Time_On_Minute";
	
	/** 定时关机. */
	public final static String TIME_OFF_MINUTE = "Time_Off_Minute";
	
	/** 是否启用倒计时. */
	public final static String COUNT_DOWN_ON_OFF = "CountDown_OnOff";
	
	/** 倒计时. */
	public final static String COUNT_DOWN_MINUTE = "CountDown_Minute";
	
	/** 能耗. */
	public final static String POWER_CONSUMPTION = "Power_Consumption";
	
	/** 是否启用定时. */
	public final static String TIME_ON_OFF = "Time_OnOff";
} public class DensityUtil {

    /** 
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
     */  
    public static int dip2px(Context context, float dpValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }  

    /** 
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
     */  
    public static int px2dip(Context context, float pxValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }  
} public class DialogManager {

	/**
	 * Gets the no network dialog.
	 * 
	 * @param ctx
	 *            the ctx
	 * @return the no network dialog
	 */
	public static Dialog getNoNetworkDialog(Context ctx) {
		Dialog dialog = new Dialog(ctx, R.style.noBackgroundDialog);
		LayoutInflater layoutInflater = LayoutInflater.from(ctx);
		View contentView = layoutInflater.inflate(R.layout.dialog_no_network,
				null);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(contentView);
		return dialog;
	}
	

	/**
	 * 注销对话框.
	 *
	 * @param ctx the ctx
	 * @param r            右按钮监听器
	 * @return the logout dialog
	 */
	public static Dialog getLogoutDialog(final Activity ctx, OnClickListener r) {
		final Dialog dialog = new Dialog(ctx, R.style.noBackgroundDialog) {
		};
		LayoutInflater layoutInflater = LayoutInflater.from(ctx);
		View v = layoutInflater.inflate(R.layout.dialog_logout, null);
		Button leftBtn = (Button) v.findViewById(R.id.left_btn);
		Button rightBtn = (Button) v.findViewById(R.id.right_btn);
		leftBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dismissDialog(ctx, dialog);
			}
		});
		rightBtn.setOnClickListener(r);

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.setContentView(v);
		return dialog;
	}
	
	/**
	 * 连接断开对话框.
	 * 
	 * @param ctx
	 *            the ctx
	 * @param r
	 *            钮监听器
	 * @return the logout dialog
	 */
	public static Dialog getDisconnectDialog(final Activity ctx, OnClickListener r) {
		final Dialog dialog = new Dialog(ctx, R.style.noBackgroundDialog) {
		};
		LayoutInflater layoutInflater = LayoutInflater.from(ctx);
		View v = layoutInflater.inflate(R.layout.dialog_disconnect, null);
		Button btnConfirm = (Button) v.findViewById(R.id.btn_confirm);
		btnConfirm.setOnClickListener(r);

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.setContentView(v);
		return dialog;
	}
	
	/**
	 * 删除对话框.
	 *
	 * @param ctx the ctx
	 * @param r            右按钮监听器
	 * @return the unbind dialog
	 */
	public static Dialog getUnbindDialog(final Activity ctx, OnClickListener r) {
		final Dialog dialog = new Dialog(ctx, R.style.noBackgroundDialog) {
		};
		LayoutInflater layoutInflater = LayoutInflater.from(ctx);
		View v = layoutInflater.inflate(R.layout.dialog_unbind, null);
		Button leftBtn = (Button) v.findViewById(R.id.left_btn);
		Button rightBtn = (Button) v.findViewById(R.id.right_btn);
		leftBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dismissDialog(ctx, dialog);
			}
		});
		rightBtn.setOnClickListener(r);

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.setContentView(v);
		return dialog;
	}
	
	/**
	 * 确定关机对话框
	 * 
	 * @param ctx
	 * @param contentStr
	 *            对话框内容
	 * @param r
	 *            右按钮监听器
	 * @return
	 */
	public static Dialog getPowerOffDialog(final Activity ctx, OnClickListener r) {
		final Dialog dialog = new Dialog(ctx, R.style.noBackgroundDialog) {
		};
		LayoutInflater layoutInflater = LayoutInflater.from(ctx);
		View v = layoutInflater.inflate(R.layout.dialog_power_off, null);
		Button leftBtn = (Button) v.findViewById(R.id.left_btn);
		Button rightBtn = (Button) v.findViewById(R.id.right_btn);
		leftBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dismissDialog(ctx, dialog);
			}
		});
		rightBtn.setOnClickListener(r);

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.setContentView(v);
		return dialog;
	}
	
	/**
	 * 确定修改密码对话框
	 * 
	 * @param ctx
	 * @param contentStr
	 *            对话框内容
	 * @param r
	 *            右按钮监听器
	 * @return
	 */
	public static Dialog getPswChangeDialog(final Activity ctx, OnClickListener r) {
		final Dialog dialog = new Dialog(ctx, R.style.noBackgroundDialog) {
		};
		LayoutInflater layoutInflater = LayoutInflater.from(ctx);
		View v = layoutInflater.inflate(R.layout.dialog_psw_change, null);
		Button leftBtn = (Button) v.findViewById(R.id.left_btn);
		Button rightBtn = (Button) v.findViewById(R.id.right_btn);
		leftBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dismissDialog(ctx, dialog);
			}
		});
		rightBtn.setOnClickListener(r);

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.setContentView(v);
		return dialog;
	}

	/**
	 * 设备故障无法使用,拨打客服热线 对话框.
	 *
	 * @param ctx the ctx
	 * @param contentStr            对话框内容
	 * @param r            右按钮监听器
	 * @return the device errir dialog
	 */
	public static Dialog getDeviceErrirDialog(final Activity ctx,
			String contentStr, OnClickListener r) {
		final Dialog dialog = new Dialog(ctx, R.style.noBackgroundDialog) {
		};
		LayoutInflater layoutInflater = LayoutInflater.from(ctx);
		View v = layoutInflater.inflate(R.layout.dialog_alarm_for_conditioner,
				null);
		TextView content = (TextView) v.findViewById(R.id.fault_content);
		Button leftBtn = (Button) v.findViewById(R.id.fault_left_btn);
		Button rightBtn = (Button) v.findViewById(R.id.fault_right_btn);

		content.setText(contentStr);
		leftBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dismissDialog(ctx, dialog);
			}
		});
		rightBtn.setOnClickListener(r);

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.setContentView(v);
		return dialog;
	}

	/**
	 * 定时对话框.
	 *
	 * @param ctx the ctx
	 * @param l the l
	 * @param titleStr the title str
	 * @param index the index
	 * @return the wheel timing dialog
	 */
	public static Dialog get2WheelTimingDialog(final Activity ctx,
			final On2TimingChosenListener l, String titleStr, int indexOne,int indexTwo) {
		
		DisplayMetrics metric = new DisplayMetrics();
		ctx.getWindowManager().getDefaultDisplay().getMetrics(metric);
		int width = metric.widthPixels; 
		
		final Dialog dialog = new Dialog(ctx, R.style.noBackgroundDialog) {
		};
		LayoutInflater layoutInflater = LayoutInflater.from(ctx);
		View v = layoutInflater.inflate(
				R.layout.dialog_2choose_timing_conditioner, null);
		TextView title = (TextView) v.findViewById(R.id.wifiSSID_tv);
		title.setText(titleStr);
		Button confi_btn = (Button) v.findViewById(R.id.confi_btn);
		Button cancel_btn = (Button) v.findViewById(R.id.cancel_btn);
		cancel_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dismissDialog(ctx, dialog);
			}
		});
		
		final WheelView wheelveiew = (WheelView) v
				.findViewById(R.id.wheel_view_timing);
		final WheelView wheelveiewMin = (WheelView) v
				.findViewById(R.id.wheel_view_timing_min);
		
		if(width<=540){
			wheelveiew.setTEXT_SIZE(30);
			wheelveiew.setADDITIONAL_ITEM_HEIGHT(60);
			wheelveiew.setADDITIONAL_ITEMS_SPACE(5);
			
			wheelveiewMin.setTEXT_SIZE(30);
			wheelveiewMin.setADDITIONAL_ITEM_HEIGHT(60);
			wheelveiewMin.setADDITIONAL_ITEMS_SPACE(5);
		}
		
		wheelveiew.setAdapter(new NumericWheelAdapter(0,23));
		wheelveiew.setCyclic(true);
		wheelveiew.setLabel(":");
		// 初始化时显示的数据
		wheelveiew.setCurrentItem(indexOne);
		
		wheelveiewMin.setAdapter(new NumericWheelAdapter(0,59,"%02d"));
		wheelveiewMin.setCyclic(true);
		// 初始化时显示的数据
		wheelveiewMin.setCurrentItem(indexTwo);
		
		confi_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int indexHour = wheelveiew.getCurrentItem();
				int indexMin = wheelveiewMin.getCurrentItem();
				l.timingChosen(indexHour,indexMin);
				dismissDialog(ctx, dialog);
			}
		});
		
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.setContentView(v);
		return dialog;
	}

	/**
	 * 延时对话框.
	 *
	 * @param ctx the ctx
	 * @param l the l
	 * @param titleStr the title str
	 * @param index the index
	 * @return the wheel timing dialog
	 */
	public static Dialog getWheelTimingDialog(final Activity ctx,
			final OnTimingChosenListener l, String titleStr, int index) {
		
		DisplayMetrics metric = new DisplayMetrics();
		ctx.getWindowManager().getDefaultDisplay().getMetrics(metric);
		int width = metric.widthPixels; 
		
		final Dialog dialog = new Dialog(ctx, R.style.noBackgroundDialog) {
		};
		LayoutInflater layoutInflater = LayoutInflater.from(ctx);
		View v = layoutInflater.inflate(
				R.layout.dialog_choose_timing_conditioner, null);
		TextView title = (TextView) v.findViewById(R.id.wifiSSID_tv);
		title.setText(titleStr);
		Button confi_btn = (Button) v.findViewById(R.id.confi_btn);
		Button cancel_btn = (Button) v.findViewById(R.id.cancel_btn);
		final WheelView wheelveiew = (WheelView) v
				.findViewById(R.id.wheel_view_timing);
		
		if(width<=540){
			wheelveiew.setTEXT_SIZE(30);
			wheelveiew.setADDITIONAL_ITEM_HEIGHT(60);
			wheelveiew.setADDITIONAL_ITEMS_SPACE(5);
		}
		
		wheelveiew.setAdapter(new NumericWheelAdapter(0,23));
		wheelveiew.setCyclic(true);
		wheelveiew.setLabel("h后");
		// 初始化时显示的数据
		wheelveiew.setCurrentItem(index);
		cancel_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dismissDialog(ctx, dialog);
			}
		});
		confi_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int index = wheelveiew.getCurrentItem();
				l.timingChosen(index);
				dismissDialog(ctx, dialog);
			}
		});

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.setContentView(v);
		return dialog;
	}
	
	/**
	 * Show dialog.
	 *
	 * @param ctx the ctx
	 * @param dialog the dialog
	 */
	public static void showDialog(Context ctx, Dialog dialog) {
		if (dialog != null && !dialog.isShowing() && ctx != null
				&& !((Activity) ctx).isFinishing()) {
			dialog.show();
		}
	}

	/**
	 * 隐藏dialog，加了context生命判断，避免窗口句柄泄漏.
	 *
	 * @param ctx            dialog依赖的activity
	 * @param dialog            欲隐藏的dialog
	 */
	public static void dismissDialog(Activity ctx, Dialog dialog) {
		if (dialog != null && dialog.isShowing() && ctx != null
				&& !ctx.isFinishing())
			dialog.dismiss();
	}

	/**
	 * wheel view dialog.
	 *
	 * @see OnTimingChosenEvent
	 */

	public interface On2TimingChosenListener {
		
		/**
		 * Timing hour chosen.
		 *
		 * @param HourTime the hour time
		 * 
		 * @param HourTime the hour time
		 */
		public void timingChosen(int HourTime,int MinTime);
		
	}
	
	/**
	 * wheel view dialog.
	 *
	 * @see OnTimingChosenEvent
	 */

	public interface OnTimingChosenListener {
		
		/**
		 * Timing chosen.
		 *
		 * @param time the time
		 */
		public void timingChosen(int time);
	}
} public class AboutVersionActivity extends BaseActivity implements OnClickListener {


	/** The btn_back. */
	ImageView iv_back;
	TextView tv_VersionCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_version);
		//actionBar.setDisplayHomeAsUpEnabled(true);
		// setManager = new SettingManager(this);
		initView();
		initEvents();

	}

	/**
	 * Inits the view.
	 */
	private void initView() {
		iv_back = (ImageView) findViewById(R.id.ivBack);
		tv_VersionCode = (TextView) findViewById(R.id.versionCode);
	}

	/**
	 * Inits the events.
	 */
	private void initEvents() {
		iv_back.setOnClickListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		tv_VersionCode.setText("V" + XPGWifiSDK.sharedInstance().getVersion().toString());
	}



	@Override
	public void onClick(View v) {
		if (v == iv_back) {
			finish();
		}

	}
} public class IntentUtils {
	private static IntentUtils instance = null;

	/** 返回该类的一个实例 */
	public static IntentUtils getInstance() {
		if (instance == null) {
			synchronized (IntentUtils.class) {
				if (instance == null)
					instance = new IntentUtils();
			}
		}
		return instance;
	}
	
//	/**
//	 * 安装APK
//	 * @param context
//	 * @param file APK文件对象
//	 */
//	public void installApk( Context ctx, File file )
//	{
//		Intent intent = new Intent();
//
//		intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
//		intent.setAction( android.content.Intent.ACTION_VIEW );
//
//		/* 调用getMIMEType()来取得MimeType */
//		String type = MimeTypeUtils.getMIMEType( file );
//
//		/* 设置intent的file与MimeType */
//		intent.setDataAndType( Uri.fromFile( file ), type );
//
//		ctx.startActivity( intent );
//	}
	
	/** 
	 * 判断是否已经安装某个应用
	 * 
	 * @param packageName 应用程序的包名
	 * @return
	 */
	public boolean existPackage( Context ctx, String packageName )
	{
		try {
			PackageManager pm = ctx.getPackageManager();
			pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
			return true;
		} catch (NameNotFoundException e) {
		     e.printStackTrace();
		     return false;
		}
	}
	
	/**
	 * 启动某个应用程序
	 * @param ctx
	 * @param packageName 应用程序的包名
	 */
	public void startPackage( Context ctx, String packageName )
	{
		Intent intent = ctx.getPackageManager().getLaunchIntentForPackage( packageName );
		if(intent != null)
		{
			intent.addFlags( Intent.FLAG_ACTIVITY_REORDER_TO_FRONT );
			ctx.startActivity( intent );
		}
	}
	
	/**
	 * 调用系统的分享程序
	 * @param ctx
	 * @param tip 分享内容
	 */
	public void share( Context ctx, String tip )
	{
		Intent intent = new Intent( Intent.ACTION_SEND );
		intent.setType( "text/plain" );
//		intent.putExtra( Intent.EXTRA_SUBJECT, "分享" ); //将以彩信形式
		intent.putExtra( Intent.EXTRA_TEXT, tip );
		ctx.startActivity( Intent.createChooser( intent, "分享" ) );
	}
	
	

	/**
	 * 打开系统的浏览器浏览网页
	 * @param context
	 * @param url
	 */
	public void startSystemBrowser( Context ctx, String url )
	{
		try {
			Uri uri = Uri.parse( url );
			Intent it = new Intent();
			it.setAction( "android.intent.action.VIEW" );
			it.setData( uri );
			it.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
			it.setClassName( "com.android.browser",
					"com.android.browser.BrowserActivity" );
			ctx.startActivity( it );
		}
		catch(Exception e) {
			startBrowser(url, ctx);
		}
		
	}

	/**
	 * 打开浏览器
	 * @param url
	 * @param context
	 */
	public void startBrowser( String url, Context ctx )
	{
		Uri uri = Uri.parse( url );
		Intent it = new Intent( Intent.ACTION_VIEW, uri );
		ctx.startActivity( it );
	}

	/**
	 * 启动某个Activity
	 * @param context
	 * @param cls
	 */
	public void startActivity( Context ctx, Class cls )
	{
		/* new一个Intent对象，并指定class */
		Intent intent = new Intent();
		intent.setClass( ctx, cls );
		/* 调用Activity */
		ctx.startActivity( intent );
	}

	/** 跳转到系统发短信界面 */
	public void gotoSystemSendMessage( Context ctx, String number, String body )
	{
		Intent intent = null;
		if(StringUtils.isEmpty( number ))
			intent = new Intent( Intent.ACTION_SENDTO, Uri.parse( "smsto:" ) );
		else
			intent = new Intent( Intent.ACTION_SENDTO, Uri.parse( "smsto:" + number ) );
		intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
		
		if(!StringUtils.isEmpty( body ))
			intent.putExtra( "sms_body", body );
		intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
		ctx.startActivity( intent );
	}

	/** 跳转到系统发彩信界面 */
	public void gotoSendMMS( Context ctx, String number )
	{
		Intent intent = new Intent( Intent.ACTION_SENDTO, Uri.fromParts(
				"mmsto", number, null ) );
		intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
		ctx.startActivity( intent );
	}

	
	/**
	 * 回收该类的数据资源
	 */
	public static void recycle()
	{
		instance = null;
	}
} public class StringUtils {

	/** 字符串编码 */
	public static final String ENCODING_UTF8 = "utf-8";

	/**
	 * 返回一个StringBuffer对象
	 * 
	 * @return 返回StringBuffer对象,长度50
	 * */
	public static StringBuffer getBuffer() {
		return new StringBuffer(50);
	}

	/**
	 * 
	 * 返回一个指定长度的StringBuffer对象
	 * 
	 * @param length
	 *            指定长度
	 * 
	 * @return 返回StringBuffer对象
	 * */
	public static StringBuffer getBuffer(int length) {
		return new StringBuffer(length);
	}

	/**
	 * 判断字符串是否为null或者为空
	 * 
	 * @param str
	 *            传入的字符串
	 * @return boolean true or false
	 * */
	public static boolean isEmpty(String str) {
		if (str == null || str == "" || str.trim().equals(""))
			return true;
		return false;
	}

	/**
	 * 判断字符串是否为0或者为空
	 * 
	 * @param str
	 *            传入的字符串
	 * @return boolean true or false
	 * */
	public static boolean isNumEmpty(String str) {
		if (str == null || str == "" || str.trim().equals("")
				|| str.trim().equals("0"))
			return true;
		return false;
	}

	/**
	 * 将一个字符串进行UTF8编码后返回
	 * 
	 * @param data
	 *            传入的字符串
	 * @return String
	 * */
	public static String encode(String data) {
		try {
			return URLEncoder.encode(data, ENCODING_UTF8);
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}

	/**
	 * 将字符串转移成整数
	 * 
	 * @param num
	 *            传入的字符串
	 * @return int
	 * */
	public static int toInt(String num) {
		try {
			return Integer.parseInt(num);
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 将字符串转移成长整数
	 * 
	 * @param num
	 *            传入的字符串
	 * @return long
	 * */
	public static long toLong(String num) {
		try {
			return Long.parseLong(num);
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 将字符串转移成浮点数
	 * 
	 * @param num
	 *            传入的字符串
	 * @return long
	 * */
	public static float toFloat(String num) {
		try {
			return Float.parseFloat(num);
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 将字符串转移成布尔数
	 * 
	 * @param num
	 *            传入的字符串
	 * @return boolean
	 * */
	public static boolean toBoolean(String num) {
		if (isEmpty(num))
			return false;
		if (num.equals("true"))
			return true;
		return false;
	}

	/**
	 * sql特殊字符转义
	 * 
	 * @param keyWord
	 *            关键字
	 * 
	 * @return 转义后的字符串
	 * */
	public static String sqliteEscape(String keyWord) {
		keyWord = keyWord.replace("/", "//");
		keyWord = keyWord.replace("'", "''");
		keyWord = keyWord.replace("[", "/[");
		keyWord = keyWord.replace("]", "/]");
		keyWord = keyWord.replace("%", "/%");
		keyWord = keyWord.replace("&", "/&");
		keyWord = keyWord.replace("_", "/_");
		keyWord = keyWord.replace("(", "/(");
		keyWord = keyWord.replace(")", "/)");
		return keyWord;
	}

	/**
	 * sql特殊字符反转义
	 * 
	 * @param keyWord
	 *            关键字
	 * 
	 * @return 反转义后的字符串
	 * */
	public static String sqliteUnEscape(String keyWord) {
		keyWord = keyWord.replace("//", "/");
		keyWord = keyWord.replace("''", "'");
		keyWord = keyWord.replace("/[", "[");
		keyWord = keyWord.replace("/]", "]");
		keyWord = keyWord.replace("/%", "%");
		keyWord = keyWord.replace("/&", "&");
		keyWord = keyWord.replace("/_", "_");
		keyWord = keyWord.replace("/(", "(");
		keyWord = keyWord.replace("/)", ")");
		return keyWord;
	}

	/**
	 * 格式一个日期
	 * 
	 * @param longDate
	 *            需要格式日期的长整数的字符串形式
	 * @param format
	 *            格式化参数
	 * @return 格式化后的日期
	 */
	public static String getStrDate(String longDate, String format) {
		if (isEmpty(longDate))
			return "";
		long time = Long.parseLong(longDate);
		Date date = new Date(time);
		return getStrDate(date, format);
	}

	/**
	 * 格式一个日期
	 * 
	 * @param time
	 *            需要格式日期的长整数
	 * @param format
	 *            格式化参数
	 * @return 格式化后的日期
	 */
	public static String getStrDate(long time, String format) {
		Date date = new Date(time);
		return getStrDate(date, format);
	}

	/**
	 * 返回当前日期的格式化表示
	 * 
	 * @param date
	 *            指定格式化的日期
	 * @param formate
	 *            格式化参数
	 * @return 格式化后的日期
	 */
	public static String getStrDate(Date date, String formate) {
		SimpleDateFormat dd = new SimpleDateFormat(formate);
		return dd.format(date);
	}

	/**
	 * 
	 * 返回当前日期的格式化（yyyy-MM-dd）表示
	 * 
	 * @return 格式化的字符串
	 * 
	 * */
	public static String getStrDate() {
		SimpleDateFormat dd = new SimpleDateFormat("yyyy-MM-dd");
		return dd.format(new Date());
	}

	/**
	 * 返回指定个数的随机数字串
	 * 
	 * @param num
	 *            随机数的位数
	 * @return String
	 * 
	 * */
	public static String getRandomStr(int num) {
		StringBuffer temp = new StringBuffer();
		Random rand = new Random();
		for (int i = 0; i < num; i++) {
			temp.append(rand.nextInt(10));
		}
		return temp.toString();
	}

}
import java.util.concurrent.ConcurrentHashMap;
import org.json.JSONException;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.gizwits.framework.activity.BaseActivity;
import com.gizwits.framework.activity.account.UserManageActivity;
import com.gizwits.framework.activity.device.DeviceListActivity;
import com.gizwits.framework.activity.device.DeviceManageListActivity;
import com.gizwits.framework.activity.help.AboutActivity;
import com.gizwits.framework.activity.help.HelpActivity;
import com.gizwits.framework.adapter.MenuDeviceAdapter;
import com.gizwits.framework.config.JsonKeys;
import com.gizwits.framework.utils.DensityUtil;
import com.gizwits.framework.utils.DialogManager;
import com.gizwits.framework.widget.AboutVersionActivity;
import com.gizwits.framework.widget.SlidingMenu;
import com.gizwits.framework.widget.SlidingMenu.SlidingMenuListener;
import com.xpg.common.system.IntentUtils;
import com.xpg.common.useful.StringUtils;
import com.gizwits.powersocket.R;
import com.xtremeprog.xpgconnect.XPGWifiDevice;
/**
 * Project Name:XPGSdkV4AppBase
 * File Name:MainControlActivity.java
 * Package Name:com.gizwits.aircondition.activity.control
 * Date:2015-1-27 14:44:17
 * Copyright (c) 2014~2015 Xtreme Programming Group, Inc.
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.gizwits.powersocket.activity.control;




// TODO: Auto-generated Javadoc
/**
 * Created by Lien on 14/12/21.
 * 
 * 设备主控界面
 * 
 * @author Lien
 */
public class MainControlActivity extends BaseActivity implements OnClickListener, SlidingMenuListener {

	/** The tag. */
	private final String TAG = "MainControlActivity";

	/** The m view. */
	private SlidingMenu mView;

	/** The iv menu. */
	private ImageView ivMenu;

	/** The tv Consumption. */
	private TextView tvConsumption;

	/** The tv Timing. */
	private TextView tvTiming;

	/** The tv Delay. */
	private TextView tvDelay;

	/** The btn Power. */
	private Button btnPower;

	/** The btn Appoinment. */
	private Button btnAppoinment;

	/** The linearLayout Timing. */
	private LinearLayout llTiming;

	/** The linearLayout Delay. */
	private LinearLayout llDelay;

	/** The m PowerOff dialog. */
	private Dialog mPowerOffDialog;

	/** The progress dialog. */
	private ProgressDialog progressDialogRefreshing;

	/** The disconnect dialog. */
	private Dialog mDisconnectDialog;

	/** 获取状态超时时间 */
	private int GetStatueTimeOut = 30000;

	/** 登陆设备超时时间 */
	private int LoginTimeOut = 5000;

	/** 是否超时标志位 */
	private boolean isTimeOut = false;

	/** The m adapter. */
	private MenuDeviceAdapter mAdapter;

	/** The lv device. */
	private ListView lvDevice;

	/**
	 * ClassName: Enum handler_key. <br/>
	 * <br/>
	 * date: 2014-11-26 17:51:10 <br/>
	 * 
	 * @author Lien
	 */
	private enum handler_key {

		/** 更新UI界面 */
		UPDATE_UI,

		/** 显示警告 */
		ALARM,

		/** 设备断开连接 */
		DISCONNECTED,

		/** 接收到设备的数据 */
		RECEIVED,

		/** 获取设备状态 */
		GET_STATUE,

		/** 获取设备状态超时 */
		GET_STATUE_TIMEOUT,

		/** The login start. */
		LOGIN_START,

		/**
		 * The login success.
		 */
		LOGIN_SUCCESS,

		/**
		 * The login fail.
		 */
		LOGIN_FAIL,

		/**
		 * The login timeout.
		 */
		LOGIN_TIMEOUT,
	}

	/**
	 * The handler.
	 */
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			handler_key key = handler_key.values()[msg.what];
			switch (key) {

			case RECEIVED:
				if (deviceDataMap==null) {
					return;
				} else {
					for (String myKey : deviceDataMap.keySet()) {
						Log.e("Map", "key=" + myKey + ",value=" + deviceDataMap.get(myKey));
					}
					try {
						if (deviceDataMap.get("data") != null) {
							Log.i("info", (String) deviceDataMap.get("data"));
							inputDataToMaps(statuMap, (String) deviceDataMap.get("data"));
						}
						// 返回主线程处理P0数据刷新
						handler.sendEmptyMessage(handler_key.UPDATE_UI.ordinal());
						handler.sendEmptyMessage(handler_key.ALARM.ordinal());
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			case UPDATE_UI:
				if (mView.isOpen())
					break;

				if (statuMap != null && statuMap.size() > 0) {
					handler.removeMessages(handler_key.GET_STATUE_TIMEOUT.ordinal());

					// 开关更新
					updatePower((Boolean) statuMap.get(JsonKeys.ON_OFF));
					// 能耗更新
					String consumption = (String) statuMap.get(JsonKeys.POWER_CONSUMPTION);
					if (!StringUtils.isEmpty(consumption))
						setConsumption(Integer.parseInt(consumption));
					// 定时更新
					boolean isTurnOn = (Boolean) statuMap.get(JsonKeys.TIME_ON_OFF);
					String minOn = (String) statuMap.get(JsonKeys.TIME_ON_MINUTE);
					String minOff = (String) statuMap.get(JsonKeys.TIME_OFF_MINUTE);
					if (!StringUtils.isEmpty(minOn) && !StringUtils.isEmpty(minOff))
						setTiming(isTurnOn, Integer.parseInt(minOn), Integer.parseInt(minOff));
					// 延时更新
					isTurnOn = (Boolean) statuMap.get(JsonKeys.COUNT_DOWN_ON_OFF);
					String min = (String) statuMap.get(JsonKeys.COUNT_DOWN_MINUTE);
					if (!StringUtils.isEmpty(min))
						setDelay(isTurnOn, Integer.parseInt(min));

					DialogManager.dismissDialog(MainControlActivity.this, progressDialogRefreshing);