MyApp.java 17.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
package com.ectrip.cyt.config;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Application;
import android.app.Dialog;
import android.bluetooth.BluetoothSocket;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources.NotFoundException;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
import android.widget.EditText;
import android_serialport_api.SerialPort;
import android_serialport_api.SerialPortFinderHandset;
import android_serialport_api.SerialPortHandset;
import android_serialport_api.SerialPortNewHandset;
import android_serialport_pos_id_api.SerialIdCardPort;

import com.basewin.base.application.BaseApplication;
import com.basewin.commu.exception.InitException;
import com.basewin.commu.tools.XMLmanager;
import com.basewin.database.DataBaseManager;
import com.basewin.define.CurrTranParam;
import com.basewin.define.FieldInfo;
import com.basewin.define.TermParam;
import com.basewin.define.TranParam;
import com.basewin.exception.CrashHandler;
import com.basewin.services.ServiceManager;
import com.basewin.utils.AppUtil;
import com.basewin.utils.GlobalTransData;
import com.basewin.widgets.ViewSet;
import com.ectrip.cyt.bean.ConfigBean;
import com.ectrip.cyt.constant.LogoType;
import com.ectrip.cyt.constant.constant;
import com.ectrip.cyt.db.DbHelper;
import com.ectrip.cyt.db.DbManager;
import com.ectrip.cyt.exceptionsave.debug.SystemCrashLog;
import com.ectrip.cyt.response.DetectVersionResponse;
import com.ectrip.cyt.utils.AESEncryptor;
import com.ectrip.cyt.utils.LogUtil;
import com.ectrip.cyt.utils.SharedPreferences2Obj;
import com.hdx.lib.printer.SerialPrinter;
import com.hdx.lib.serial.SerialParam;
import com.hdx.lib.serial.SerialPortOperaion;
import com.hdx.lib.serial.SerialPortOperaion.SerialReadData;


public class MyApp extends BaseApplication {
	private static final String TAG = "MyApp";
	private static MyApp instance;
	// 是否是手持机
	public boolean isHandset = false;
	public String KeyStr = "1234";
	private String idCard = ""; // 身份证号


	// 记录全部的activity
	private List<Activity> activitys = null;

	public Object lock;

	private DetectVersionResponse updateBean;

	/*************************** 下面是2.0的变量声明 *******************************************/
	private String ver = "";// 版本号

	private String verType = ""; // 版本号 畅游通CT 备份QT
	private String signkey = ""; // 标识
	private String identity = ""; // 编码
	private int printNum = -1;// 打印次数
	private boolean isBluConnection = false;// 是否连接蓝牙打印机中
	private BluetoothSocket bluetoothSocket;// 蓝牙socket
	private Integer type = null;// 设备类型
	private String ServiceIp = "";// w.ljw.com
	private int checkType = -1;//检票方式  0:二维码
	private HashMap<String,String> pid = null; //订单流水号

	public void setPid(HashMap<String,String> pid) {
		this.pid = pid;
	}

	public HashMap<String,String> getPid() {

		return pid;
	}

	private Long accountId; //操作员ID
	private String username;

	public void setUsername(String username) {
		this.username = username;
	}

	public String getUsername() {

		return username;
	}

	public Long getAccountId() {
		return accountId;
	}

	public void setAccountId(Long accountId) {
		this.accountId = accountId;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;
		SystemCrashLog.init(this);
		lock = new Object();
		setVer();// 获取版本号
		setVerType();// 获取版本类型
		activitys = new LinkedList<Activity>();
		isHandset = DevicTool.getInstance().isSerialPortHandset();
		if (android.os.Build.MODEL.equals("P2000L")){
			ServiceManager.getInstence().init(this.getApplicationContext());
		}
	}

	public static MyApp getInstance() {
		return instance;
	}

	public void setVer() { // 获取版本号,当获取第一次失败情况下,再获取一遍
		PackageInfo info;
		try {
			info = instance.getPackageManager().getPackageInfo(
					instance.getPackageName(), 0);
			ver = info.versionName;
		} catch (NameNotFoundException e) {
			try {
				info = instance.getPackageManager().getPackageInfo(
						instance.getPackageName(), 0);
				ver = info.versionName;
			} catch (NameNotFoundException e1) {
				ver = "1.0";
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}

	public String getVer() {
		if (ver.equals("")) {
			PackageInfo info;
			try {
				info = instance.getPackageManager().getPackageInfo(
						instance.getPackageName(), 0);
				ver = info.versionName;
			} catch (NameNotFoundException e) {
				try {
					info = instance.getPackageManager().getPackageInfo(
							instance.getPackageName(), 0);
					ver = info.versionName;
				} catch (NameNotFoundException e1) {
					ver = "1.0";
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
		}
		return ver;
	}


	public int getCheckType() {
		return checkType;
	}

	public void setCheckType(int checkType) {
		this.checkType = checkType;
	}

	public void setVerType() { // 版本类型 畅游通:CT 备用: QT
		if (constant.logoMark == LogoType.CYT.getValue()||constant.logoMark == LogoType.EMC.getValue()) {
			verType = "CT";
		} else if (constant.logoMark == LogoType.QNE.getValue()) { // 目前QT就是去哪儿
			verType = "QT";
		}
	}

	public String getVerType() {
		if (verType.equals("")) {
			if (constant.logoMark == LogoType.CYT.getValue()||constant.logoMark == LogoType.EMC.getValue()) {
				verType = "CT";
			} else if (constant.logoMark == LogoType.QNE.getValue()) { // 目前QT就是去哪儿
				verType = "QT";
			}
		}
		return verType;
	}

	public String getSignkey() {
		if (signkey == null) {
			ArrayList<ConfigBean> listConfig;
			listConfig = DbManager.GetConfigs();
			if (listConfig != null && listConfig.size() > 0) {
				try {
					signkey = AESEncryptor.decrypt("41227677", listConfig
							.get(0).getEc_signkey());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return signkey;
	}

	public void setSignkey(String signkey) {
		this.signkey = signkey;
	}

	public String getIdentity() {
		if (identity == null) {
			try {
				ArrayList<ConfigBean> listConfig;
				listConfig = DbManager.GetConfigs();
				if (listConfig != null && listConfig.size() > 0) {
					identity = listConfig.get(0).getEc_identity();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return identity;
	}

	public void setIdentity(String identity) {
		this.identity = identity;
	}

	public int getPrintNum() {
		try {
			printNum = SharedPreferences2Obj.getInstance(this)
					.setName("MachineType")
					.getObject("printNum", Integer.class);
			if (printNum > 3) {
				printNum = 3;
				SharedPreferences2Obj.getInstance(this).setName("MachineType")
						.setObject("printNum", printNum);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (printNum == -1) {
			printNum = 2;
		}
		return printNum;
	}

	public void setPrintNum(int printNum) {
		this.printNum = printNum;
	}

	public boolean isBluConnection() {
		return isBluConnection;
	}

	public void setBluConnection(boolean isBluConnection) {
		this.isBluConnection = isBluConnection;
	}

	public BluetoothSocket getBluetoothSocket() {
		return bluetoothSocket;
	}

	public void setBluetoothSocket(BluetoothSocket bluetoothSocket) {
		this.bluetoothSocket = bluetoothSocket;
	}

	/** 检测网络连接状态 */
	public boolean checkNetwork() {
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null)
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED)
						return true;
				}
		}
		return false;
	}

	public SharedPreferences savePreToSDcard(String name) {
		try {
			Field field;
			// 获取ContextWrapper对象中的mBase变量。该变量保存了ContextImpl对象
			field = ContextWrapper.class.getDeclaredField("mBase");
			field.setAccessible(true);
			// 获取mBase变量
			Object obj = field.get(this);
			// 获取ContextImpl。mPreferencesDir变量,该变量保存了数据文件的保存路径
			field = obj.getClass().getDeclaredField("mPreferencesDir");
			field.setAccessible(true);
			// 创建自定义路径
			File file = null;
			String storageState1 = Environment.getExternalStorageState();
			if (storageState1.equals(Environment.MEDIA_MOUNTED)) {

				String savePath = Environment.getExternalStorageDirectory()
						.getAbsolutePath() + "/ectriptrippos";
				file = new File(savePath);
				savePath += "/config";
				File file2 = new File(savePath);
				if (!file.exists()) {// 判断文件夹目录是否存在
					if (file.mkdir()) {// 如果不存在则创建
						if (!file2.exists()) {
							if (file2.mkdir()) {
								field.set(obj, file2);// 修改mPreferencesDir变量的值
							}
						} else {
							field.set(obj, file2);// 修改mPreferencesDir变量的值
						}
					}
				} else {
					if (!file2.exists()) {
						if (file2.mkdir()) {
							field.set(obj, file2);// 修改mPreferencesDir变量的值
						}
					} else {
						field.set(obj, file2);// 修改mPreferencesDir变量的值
					}
				}
			}
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		int __sdkLevel = Build.VERSION.SDK_INT;
		try {
			return getSharedPreferences(name,
					(__sdkLevel > Build.VERSION_CODES.FROYO) ? 4 : 0);
		} catch (Exception e) {
			e.printStackTrace();
			return getSharedPreferences(name, Context.MODE_PRIVATE);
		}
	}

	public String getServiceIp() {
		if (ServiceIp == null) {
			ArrayList<ConfigBean> listConfig;
			listConfig = DbManager.GetConfigs();
			if (listConfig != null && listConfig.size() > 0) {
				ServiceIp = listConfig.get(0).getEc_ip();
			} else {
				ServiceIp = "";
			}
		}
		return ServiceIp;
	}

	public void setServiceIp(String serviceIp) {
		ServiceIp = serviceIp;
	}

	/************************* 以下1.0 *********************************/

	public DetectVersionResponse getUpdateBean() {
		return updateBean;
	}

	public void setUpdateBean(DetectVersionResponse updateBean) {
		this.updateBean = updateBean;
	}

	public String getIdCard() {
		return idCard;
	}

	public void setIdCard(String idCard) {
		this.idCard = idCard;
	}

	/**
	 * 设置数据保存
	 */

	/* ==============================应用配置============================== */

	/** 确认程序是否第一次打开 */
	public boolean getOpenTime() {
		return getSharedPreferences("myapp_config", 0).getBoolean(
				"open_app_first_" + getVersion(), true);
	}

	/** 标记程序已经开启过 */
	public void setOpenTime() {
		getSharedPreferences("myapp_config", 0).edit()
				.putBoolean("open_app_first_" + getVersion(), false).commit();
	}

	/** 获取应用程序的版本号 */
	public int getVersion() {
		int oldVersion = 0;
		try {
			oldVersion = getApplicationContext()
					.getPackageManager()
					.getPackageInfo(getApplicationContext().getPackageName(), 0).versionCode;
		} catch (Exception e) {
			LogUtil.d(TAG, "获取应用版本失败");
		}
		return oldVersion;
	}

	/** 获取应用程序的版本信息 */
	public String getVersionName() {
		String oldVersion = "";
		try {
			oldVersion = getApplicationContext()
					.getPackageManager()
					.getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
		} catch (Exception e) {
			LogUtil.d(TAG, "获取应用版本信息失败");
		}
		return oldVersion;
	}

	/** 获取手机型号 */
	public String getModel() {
		return Build.MODEL;
	}

	/* ==============================数据库============================== */
	private DbHelper dbHelper;
	private SQLiteDatabase db;

	/** 获取数据库对象 */
	public synchronized DbHelper getDbHelper() {
		synchronized (lock) {
			if (dbHelper == null)
				dbHelper = new DbHelper(getApplicationContext());
		}
		return dbHelper;
	}

	/** 获取数据库编辑对象 */
	public synchronized SQLiteDatabase getDb() {
		synchronized (lock) {
			if (mOpenCounter.incrementAndGet() == 1) {
				if (db == null)
					db = getDbHelper().getWritableDatabase();
			}
		}
		return db;
	}

	public synchronized void closeDatabase() {
		synchronized (lock) {
			if (mOpenCounter.decrementAndGet() == 0) {
				if (dbHelper != null) {
					dbHelper.close();
					dbHelper = null;
				}
			}
		}
	}

	private AtomicInteger mOpenCounter = new AtomicInteger();

	public Dialog initNetWork(Context context) {
		final EditText inputpress = new EditText(context);
		inputpress.setInputType(InputType.TYPE_CLASS_TEXT
				| InputType.TYPE_TEXT_VARIATION_PASSWORD);
		Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("没有可用的网络");
		builder.setMessage("是否对网络进行设置?");
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setView(null).setPositiveButton("确定",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = null;
						try {
							@SuppressWarnings("deprecation")
							String sdkVersion = android.os.Build.VERSION.SDK;
							if (Integer.valueOf(sdkVersion) > 10) {
								intent = new Intent(
										android.provider.Settings.ACTION_SETTINGS);

							} else {
								intent = new Intent();
								ComponentName comp = new ComponentName(
										"com.android.settings",
										"com.android.settings.WirelessSettings");
								intent.setComponent(comp);
								intent.setAction("android.intent.action.VIEW");
							}
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivity(intent);
						} catch (Exception e) {
							LogUtil.i(TAG,
									"open network settings failed, please check...");
							e.printStackTrace();
						}
					}
				});

		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				dialog = null;
			}
		});
		Dialog dialog = null; // 网络弹框
		if (dialog == null) {
			dialog = builder.create();
		}

		if (type == null) {
			type = SharedPreferences2Obj.getInstance(this)
					.setName("MachineType").getObject("type", Integer.class);
		}
		if (type != null && type == 8) { // 手持机与手机类型不一样
			dialog.getWindow().setType(
					WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		}

		dialog.show();
		return dialog;
	}





	private SharedPreferences sp;

	public SharedPreferences getSp() {

		if (sp == null) {
			sp = MyApp.getInstance().getSharedPreferences("app_url", 0);
		}
		return sp;
	}

	public String getSharedpreferences(String key) {

		return sp.getString(key, "");

	}

	public void setSharedString(String key, String d) {
		if (sp == null) {
			sp = this.getSharedPreferences("app_url", 0);
		}
		sp.edit().putString(key, d).commit();

	}

	private int tempMode;

	public int getTempMode() {
		return tempMode;
	}

	public void setTempMode(int tempMode) {
		this.tempMode = tempMode;
	}



	// 添加Activity到容器中
	public void addActivity(Activity activity) {
		if (activitys != null && activitys.size() > 0) {
			if (!activitys.contains(activity)) {
				activitys.add(activity);
			}
		} else {
			activitys.add(activity);
		}
	}

	public void removeActivity(Activity activity) {
		if (activitys != null && activitys.size() > 0) {
			if (activitys.contains(activity)) {
				activitys.remove(activity);
			}
		}
	}

	// 遍历所有Activity并finish
	public void exit() {
		if (activitys != null && activitys.size() > 0) {
			for (Activity activity : activitys) {
				activity.finish();
			}
		}
		System.exit(0);
	}


	private SerialPort mSerialPort = null;

	public SerialPort getSerialPort() throws SecurityException, IOException, InvalidParameterException {
		if (mSerialPort == null) {
			/* Read serial port parameters */
			SharedPreferences sp = getSharedPreferences("android_serialport_api.sample_preferences", MODE_PRIVATE);
			String path = sp.getString("DEVICE", "/dev/ttyMT2");
			int baudrate = Integer.decode(sp.getString("BAUDRATE", "115200"));

			/* Check parameters */
			if ( (path.length() == 0) || (baudrate == -1)) {
				throw new InvalidParameterException();
			}

			/* Open the serial port */
			//	mSerialPort = new SerialPort(new File("/dev/ttySAC1"), 9600, 0);
			mSerialPort = new SerialPort(new File("/dev/ttyMT3"), 115200, 0);
//			mSerialPort = new SerialPort(new File("/dev/ttyS1"), baudrate, 0);
		}
		return mSerialPort;
	}
	public void closeSerialPort() {
		if (mSerialPort != null) {
			mSerialPort.close();
			mSerialPort = null;
		}
	}

}