public class DiskAdapter extends BaseAdapter {

	private List<Disk> list;

	private Context context;

	private int selectedPosition = -1;

	public DiskAdapter(Context context) {
		this.context = context;
	}

	public DiskAdapter(Context context, List<Disk> list) {
		this.context = context;
		this.list = list;
	}

	@Override
	public int getCount() {
		if (list == null) {
			return 0;
		}
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder viewHolder;
		if (convertView == null) {
			convertView = LayoutInflater.from(context).inflate(
					R.layout.disk_list_item, null);
			viewHolder = new ViewHolder();
			viewHolder.textView = (TextView) convertView
					.findViewById(R.id.disk_text);
			viewHolder.textSize = (TextView) convertView
					.findViewById(R.id.disk_text_size);
			viewHolder.linearLayout = (LinearLayout) convertView
					.findViewById(R.id.disk_lin);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		if (selectedPosition == position) {
			viewHolder.textView.setSelected(true);
			viewHolder.linearLayout.setBackgroundColor(context.getResources()
					.getColor(R.color.skyblue));
		} else {
			viewHolder.textView.setSelected(false);
			viewHolder.linearLayout.setBackgroundColor(Color.TRANSPARENT);
		}
		viewHolder.textView.setText(list.get(position).getFileName());
		viewHolder.textSize.setText("剩余:" + list.get(position).getFreeSpace());
		return convertView;
	}

	class ViewHolder {
		TextView textView;
		TextView textSize;
		LinearLayout linearLayout;
	}

	public int getSelectedPosition() {
		return selectedPosition;
	}

	public void setSelectedPosition(int selectedPosition) {
		this.selectedPosition = selectedPosition;
	}

	public List<Disk> getList() {
		return list;
	}

	public void setList(List<Disk> list) {
		this.list = list;
	}

} public class AppException extends Exception implements UncaughtExceptionHandler {

	public final static String LOG_TAG = "qingyang_log";

	// 错误异常类型
	public final static byte TYPE_NETWORK = 0x01;
	public final static byte TYPE_SOCKET = 0x02;
	public final static byte TYPE_HTTP_CODE = 0x03;
	public final static byte TYPE_HTTP_ERROR = 0x04;
	public final static byte TYPE_XML = 0x05;
	public final static byte TYPE_IO = 0x06;
	public final static byte TYPE_RUN = 0x07;

	private byte type;

	private int code;

	// 系统默认的UncaughtExceptionHandler处理类
	private UncaughtExceptionHandler mDefaultHandler;

	private AppException() {
		this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
	}

	private AppException(byte type, int code, Exception excp) {
		super(excp);
		this.type = type;
		this.code = code;
		this.saveErrorLog(excp);
	}

	/**
	 * 获取APP异常崩溃处理对象
	 * 
	 * @param context
	 * @return
	 */
	public static AppException getAppExceptionHandler() {
		return new AppException();
	}

	/**
	 * 友好的错误提示
	 * 
	 * @param context
	 */
	public void makeToast(Context context) {

		switch (this.getType()) {
		case TYPE_HTTP_CODE:
			String err = context.getString(R.string.http_status_code_error,
					this.getCode());
			Toast.makeText(context, err, Toast.LENGTH_SHORT).show();
			break;
		case TYPE_HTTP_ERROR:
			Toast.makeText(context,
					context.getString(R.string.http_exception_error),
					Toast.LENGTH_SHORT).show();
		case TYPE_SOCKET:
			Toast.makeText(context,
					context.getString(R.string.socket_exception_error),
					Toast.LENGTH_SHORT).show();
			break;
		case TYPE_NETWORK:
			Toast.makeText(context,
					context.getString(R.string.network_not_connected),
					Toast.LENGTH_SHORT).show();
			break;
		case TYPE_XML:
			Toast.makeText(context,
					context.getString(R.string.xml_parser_failed),
					Toast.LENGTH_SHORT).show();
			break;
		case TYPE_IO:
			Toast.makeText(context,
					context.getString(R.string.io_exception_error),
					Toast.LENGTH_SHORT).show();
			break;
		case TYPE_RUN:
			Toast.makeText(context,
					context.getString(R.string.app_run_code_error),
					Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
	}

	/**
	 * 保存错误日志
	 * 
	 * @param excp
	 */
	public void saveErrorLog(Exception excp) {
		String errorlog = Constant.LOG_NAME;
		String logFilePath = "";
		FileWriter fw = null;
		PrintWriter pw = null;
		try {

			logFilePath = FileUtil.fileDirectory(Constant.LOG_PATH, errorlog);

			// 没有挂载SD卡，无法写文件
			if (logFilePath.equals("")) {
				return;
			}
			File logFile = new File(logFilePath);

			if (!logFile.exists()) {
				logFile.createNewFile();
			}

			fw = new FileWriter(logFile, true);

			pw = new PrintWriter(fw);

			excp.printStackTrace(pw);

			pw.close();

			fw.close();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pw != null) {
				pw.close();
			}
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		// TODO
		// 异常捕获处理
		if (!handleException(ex) && mDefaultHandler != null) {
			mDefaultHandler.uncaughtException(thread, ex);
		}
	}

	public static AppException http(int code) {
		return new AppException(TYPE_HTTP_CODE, code, null);
	}

	public static AppException http(Exception e) {
		return new AppException(TYPE_HTTP_ERROR, 0, e);
	}

	public static AppException socket(Exception e) {
		return new AppException(TYPE_SOCKET, 0, e);
	}

	public static AppException io(Exception e) {
		if (e instanceof UnknownHostException || e instanceof ConnectException) {
			return new AppException(TYPE_NETWORK, 0, e);
		} else if (e instanceof IOException) {
			return new AppException(TYPE_IO, 0, e);
		}
		return run(e);
	}

	public static AppException network(Exception e) {
		if (e instanceof UnknownHostException || e instanceof ConnectException) {
			return new AppException(TYPE_NETWORK, 0, e);
		} else if (e instanceof HttpException) {
			return http(e);
		} else if (e instanceof SocketException) {
			return socket(e);
		}
		return http(e);
	}

	public static AppException xml(Exception e) {
		return new AppException(TYPE_XML, 0, e);
	}

	public static AppException run(Exception e) {
		return new AppException(TYPE_RUN, 0, e);
	}

	public byte getType() {
		return type;
	}

	public int getCode() {
		return code;
	}

	/**
	 * 自定义异常处理:收集错误信息并发送错误报告
	 * 
	 * @param ex
	 * @return 处理异常返回true否则返回false
	 */
	private boolean handleException(Throwable ex) {
		if (ex == null) {
			return false;
		}

		final Context context = AppManager.getAppManager().currentActivity();

		if (context == null) {
			return false;
		}

		final String crashReport = getCrashReport(context, ex);

		// 保存错误日志
		saveErrorLog((Exception) ex);

		new Thread(new Runnable() {

			@Override
			public void run() {
				Looper.prepare();
				UIHelper.sendAppCrashReport(context, crashReport);
				Looper.loop();
			}
		}).start();
		return true;
	}

	/**
	 * 获取app崩溃异常报告
	 * 
	 * @param context
	 * @param ex
	 * @return
	 */
	private String getCrashReport(Context context, Throwable ex) {
		PackageInfo packageInfo = ((BaseApplication) context
				.getApplicationContext()).getPackageInfo();

		StringBuffer stringBuffer = new StringBuffer();

		stringBuffer.append("Version: " + packageInfo.versionName + "("
				+ packageInfo.versionCode + ")\n");

		stringBuffer.append("Android: " + Build.VERSION.RELEASE + "("
				+ Build.MODEL + ")\n");

		stringBuffer.append("Exception: " + ex.getMessage() + "\n");

		// 异常元素集合
		StackTraceElement[] elements = ex.getStackTrace();

		for (int i = 0; i < elements.length; i++) {
			stringBuffer.append(elements[i].toString() + "\n");
		}

		return stringBuffer.toString();
	}
} public class AppManager {

	// activity的堆栈
	private static Stack<Activity> activityStack;

	private static AppManager instance;

	/**
	 * 单例
	 */
	public static AppManager getAppManager() {

		if (instance == null) {
			instance = new AppManager();
		}
		return instance;

	}

	/**
	 * 添加activity到堆栈
	 * 
	 * @param activity
	 */
	public void addActivity(Activity activity) {

		if (activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		activityStack.add(activity);
	}

	/**
	 * 获取当前activity(堆栈中最后一个压入的activity)
	 * 
	 * @return
	 */
	public Activity currentActivity() {
		Activity activity = activityStack.lastElement();
		return activity;
	}

	/**
	 * 结束当前的activity(堆栈中最后一个压入的activity)
	 */
	public void finishActivity() {
		Activity activity = activityStack.lastElement();

		finishActivity(activity);
	}

	/**
	 * 结束指定的activity
	 */
	public void finishActivity(Activity activity) {

		if (activity != null) {
			activityStack.remove(activity);
			activity.finish();
			activity = null;
		}
	}

	/**
	 * 结束所有的activity
	 */
	public void finishAllActivity() {

		for (int i = 0, size = activityStack.size(); i < size; i++) {
			if (activityStack.get(i) != null) {
				activityStack.get(i).finish();
			}
		}

		activityStack.clear();

	}

	/**
	 * 退出应用程序
	 * 
	 * @param context
	 */
	public void AppExit(Context context) {

		finishAllActivity();

		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);

		// // 2.2之前的rom就用restartPackage之后的就用killBackgroundProcesses
		if (BaseApplication.isMethodsCompat(Build.VERSION_CODES.FROYO)) {
			activityManager.killBackgroundProcesses(context.getPackageName());
		} else {

			activityManager.restartPackage(context.getPackageName());
		}

		System.exit(0);
	}
} public class BaseActivity extends Activity {

	// 是否允许全屏
	private boolean allowFullScreen = true;

	// 是否允许销毁
	private boolean allowDestory = true;

	private View view;

	// 屏幕宽度
	protected int screenWidth;

	// 屏幕高度
	protected int screenHeight;

	// 密度
	protected float density;

	// 所有的异步任务
	protected List<AsyncTask<Void, Void, Boolean>> myAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();

	protected BaseApplication application;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		allowFullScreen = true;

		AppManager.getAppManager().addActivity(this);

		application = (BaseApplication) getApplication();

		// DisplayMetrics 类提供了一种关于显示的通用信息，如显示大小，分辨率和字体
		DisplayMetrics metrics = new DisplayMetrics();

		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		screenWidth = metrics.widthPixels;

		screenHeight = metrics.heightPixels;

		density = metrics.density;

	}

	/**
	 * 添加异步任务到数组中
	 * 
	 * @param asyncTask
	 */
	public void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		myAsyncTasks.add(asyncTask.execute());
	}

	public boolean isAllowFullScreen() {
		return allowFullScreen;
	}

	/**
	 * 设置是否全屏
	 * 
	 * @param allowFullScreen
	 */
	public void setAllowFullScreen(boolean allowFullScreen) {
		this.allowFullScreen = allowFullScreen;
	}

	public void setAllowDestory(boolean allowDestory) {
		this.allowDestory = allowDestory;
	}

	public void setAllowDestory(boolean allowDestory, View view) {
		this.allowDestory = allowDestory;
		this.view = view;
	}

	/**
	 * 清除所有的异步任务
	 */
	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = myAsyncTasks
				.iterator();

		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();

			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}

		myAsyncTasks.clear();
	}

	/**
	 * 通过Class跳转界面
	 */
	protected void startActivity(Class<?> cls) {

		startActivity(cls, null);
	}

	/**
	 * 含有Bundle通过Class跳转界面
	 */
	protected void startActivity(Class<?> cls, Bundle bundle) {
		Intent intent = new Intent();

		intent.setClass(this, cls);

		if (bundle != null) {
			intent.putExtras(bundle);
		}

		startActivity(intent);
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();

		clearAsyncTask();

		// AppManager.getAppManager().finishActivity(this);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && view != null) {

			view.onKeyDown(keyCode, event);

			if (!allowDestory) {
				return false;
			}

		}

		return super.onKeyDown(keyCode, event);
	}

} public class Disk extends Base {

	private String fileName;

	private String totalSpace;

	private String freeSpace;

	private String path;

	/**
	 * 解析json字符串
	 * 
	 * @param json
	 * @return
	 */
	public static List<Disk> parse(String json) {

		List<Disk> list = new ArrayList<Disk>();

		try {

			JSONArray jsonArray = new JSONArray(json);

			for (int i = 0; i < jsonArray.length(); i++) {
				Disk disk = new Disk();

				JSONObject jsonObject = jsonArray.getJSONObject(i);

				disk.setFileName(jsonObject.getString("fileName"));

				disk.setTotalSpace(jsonObject.getString("totalSpace"));

				disk.setFreeSpace(jsonObject.getString("freeSpace"));

				disk.setPath(jsonObject.getString("path"));

				list.add(disk);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return list;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getTotalSpace() {
		return totalSpace;
	}

	public void setTotalSpace(String totalSpace) {
		this.totalSpace = totalSpace;
	}

	public String getFreeSpace() {
		return freeSpace;
	}

	public void setFreeSpace(String freeSpace) {
		this.freeSpace = freeSpace;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

} public class UIHelper {

	/**
	 * 弹出toast消息
	 * 
	 * @param context
	 * @param msg
	 */
	public static void ToastMessage(Context context, String msg) {
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}

	public static void ToastMessage(Context context, int msg) {
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 弹出toast消息(自设显示时间)
	 * 
	 * @param context
	 * @param msg
	 * @param time
	 */
	public static void ToastMessage(Context context, String msg, int time) {
		Toast.makeText(context, msg, time).show();
	}

	/**
	 * 显示登录界面
	 * 
	 * @param context
	 */
	public static void showLoginDialog(Context context) {
		Intent intent = new Intent(context, LoginDialog.class);
		context.startActivity(intent);
	}

	/**
	 * 发送App错误异常报告
	 * 
	 * @param context
	 * @param crashReport
	 */
	public static void sendAppCrashReport(final Context context,
			final String crashReport) {

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setTitle(R.string.app_error);
		builder.setMessage(R.string.app_error_message);
		builder.setPositiveButton(R.string.submit_report,
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// 发送异常报告
						Intent intent = new Intent(Intent.ACTION_SEND);
						// intent.setType("text/plain");// 模拟器
						intent.setType("message/rfc822");// 真机
						// 发送邮件 Intent.EXTRA_CC抄送 Intent.EXTRA_BCC密送者
						intent.putExtra(Intent.EXTRA_EMAIL,
								new String[] { "736909686@qq.com" });
						// 标题
						intent.putExtra(Intent.EXTRA_SUBJECT,
								"清扬android客户端-错误报告");
						// 内容
						intent.putExtra(Intent.EXTRA_TEXT, crashReport);

						context.startActivity(Intent.createChooser(intent,
								"发送错误报告"));

						AppManager.getAppManager().AppExit(context);

					}
				});

		builder.setNegativeButton(R.string.sure, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				AppManager.getAppManager().AppExit(context);
			}
		});

		AlertDialog alertDialog = builder.create();
		alertDialog.setCanceledOnTouchOutside(false);
		alertDialog.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				AppManager.getAppManager().AppExit(context);
			}
		});
		alertDialog.show();

	}

	/**
	 * 用户登录或注销
	 * 
	 * @param activity
	 */
	public static void loginOrLogout(Activity activity) {
		BaseApplication application = (BaseApplication) activity
				.getApplication();

		if (application.isLogin()) {
			application.layout();
			ToastMessage(application, "已退出登陆");
		} else {
			showLoginDialog(activity);
		}
	}

	/**
	 * 清除缓存
	 * 
	 * @param activity
	 */
	public static void clearAppCache(Activity activity) {
		final BaseApplication application = (BaseApplication) activity
				.getApplication();

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					ToastMessage(application, "缓存清除成功");
				} else {
					ToastMessage(application, "缓存清除失败");
				}
			};
		};

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message msg = new Message();

				try {
					application.clearAppCache();
					msg.what = 1;
				} catch (Exception e) {
					e.printStackTrace();

					msg.what = -1;
				}
				handler.sendMessage(msg);
			}
		}).start();

	}

	/**
	 * 清除下载数据
	 * 
	 * @param activity
	 */
	public static void clearDownCache(Activity activity) {
		final BaseApplication application = (BaseApplication) activity
				.getApplication();

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					ToastMessage(application, "清除成功");
				} else {
					ToastMessage(application, "清除失败");
				}
			};
		};

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message msg = new Message();

				try {
					application.clearDownCache();
					msg.what = 1;
				} catch (Exception e) {
					e.printStackTrace();

					msg.what = -1;
				}
				handler.sendMessage(msg);
			}
		}).start();

	}

	/**
	 * 显示检查更新页面
	 * 
	 * @param settingActivity
	 */
	public static void showFeedBack(Context context) {
		Intent intent = new Intent(context, FeedBackDialog.class);
		context.startActivity(intent);
	}

	/**
	 * 点击返回监听事件
	 * 
	 * @param activity
	 * @return
	 */
	public static View.OnClickListener finish(final Activity activity) {
		return new View.OnClickListener() {
			public void onClick(View v) {
				activity.finish();
			}
		};
	}
} public class UpdateManager {

	// 没有sd卡状态
	private static final int DOWN_NOSDCARD = 0;
	// 更新状态
	private static final int DOWN_UPDATE = 1;
	// 结束状态
	private static final int DOWN_OVER = 2;

	private static final int DIALOG_TYPE_LATEST = 0;

	private static final int DIALOG_TYPE_FAIL = 1;

	private static UpdateManager updateManager;

	private Context context;

	// 终止标记
	private boolean interceptFlag;

	// 当前版本的名称
	private String curVersionName = "";

	// 当前版本号
	private int curVersionCode;

	// 查询动画
	private ProgressDialog progressDialog;

	// 已经是最新或无法获取最新版本的对话框
	private Dialog latestOrFailDialog;

	// 服务端获取的更新信息
	private Update mUpdate;

	// 返回回来的安装包url
	private String apkUrl;

	// 提示语
	private String updateMsg;

	// 通知对话框
	private Dialog noticeDialog;

	// 下载对话框
	private Dialog downloadDialog;

	// 下载进度条
	private ProgressBar mProgressBar;

	// 下载详细文本
	private TextView mProgressText;

	// 下载线程
	private Thread downLoadThread;

	// 下载路径
	private String savePath;

	// apk文件路径
	private String apkFilePath;

	// 临时文件路径
	private String tempFilePath;

	// 进度值
	private int progress;

	// 下载文件的大小
	private String apkFileSize;

	// 已下载文件的大小
	private String tmpFileSize;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgressBar.setProgress(progress);
				mProgressText.setText(tmpFileSize + "/" + apkFileSize);
				break;

			case DOWN_OVER:
				downloadDialog.dismiss();
				downloadDialog = null;
				installApk();
				break;
			case DOWN_NOSDCARD:
				downloadDialog.dismiss();
				downloadDialog = null;
				UIHelper.ToastMessage(context, "无法下载安装文件，请检查SD卡是否挂载", 3000);
			}
		};
	};

	public static UpdateManager getUpdateManager() {
		if (updateManager == null) {
			updateManager = new UpdateManager();
		}
		updateManager.interceptFlag = false;
		return updateManager;
	}

	/**
	 * 获取当前客户端的版本信息
	 */
	private void getCurrentVersion() {
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			curVersionName = info.versionName;
			curVersionCode = info.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 检查app更新
	 * 
	 * @param context
	 * @param isShowMsg
	 *            是否显示查询dialog
	 */
	public void checkAppUpdate(final Context context, final boolean isShowMsg) {
		this.context = context;
		getCurrentVersion();
		if (isShowMsg) {
			if (progressDialog == null) {
				progressDialog = ProgressDialog.show(context, null,
						"正在检测,请稍后...", true, true);
			} else if (progressDialog.isShowing()
					|| (latestOrFailDialog != null && latestOrFailDialog
							.isShowing())) {
				return;
			}
		}

		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// 进度条对话框不显示
				if (progressDialog != null && !progressDialog.isShowing()) {
					return;
				}

				if (isShowMsg && progressDialog != null) {
					progressDialog.dismiss();
					progressDialog = null;
				}

				if (msg.what == 1) {
					mUpdate = (Update) msg.obj;

					if (mUpdate != null) {
						if (curVersionCode < mUpdate.getVersionCode()) {
							apkUrl = mUpdate.getDownloadUrl();
							updateMsg = mUpdate.getUpdateLog();
							showNoticeDialog();
						} else if (isShowMsg) {
							showLatestOrFailDialog(DIALOG_TYPE_FAIL);
						}
					}
				}
			}
		};
		new Thread(new Runnable() {

			@Override
			public void run() {
				Message msg = new Message();

				try {
					Update update = NetClient
							.checkVersion((BaseApplication) context
									.getApplicationContext());

					msg.what = 1;

					msg.obj = update;

					handler.sendMessage(msg);

				} catch (AppException e) {
					e.printStackTrace();
				}

			}
		}).start();
	}

	/**
	 * 显示已经最新或者无法获取版本信息的对话框
	 * 
	 * @param dialogTypeFail
	 */
	protected void showLatestOrFailDialog(int dialogType) {
		if (latestOrFailDialog != null) {
			latestOrFailDialog.dismiss();
			latestOrFailDialog = null;
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(context);

		builder.setTitle("系统提示");

		if (dialogType == DIALOG_TYPE_FAIL) {
			builder.setMessage("无法获取版本更新信息");
		} else if (dialogType == DIALOG_TYPE_LATEST) {
			builder.setMessage("您已经是最新版本");
		}

		builder.setPositiveButton("确定", null);
		latestOrFailDialog = builder.create();
		latestOrFailDialog.show();
	}

	/**
	 * 显示版本更新通知对话框
	 */
	private void showNoticeDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);

		builder.setTitle("软件版本更新");

		builder.setMessage(updateMsg);

		builder.setPositiveButton("立即更新", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				showDownloadDialog();
			}
		});

		builder.setNegativeButton("以后再说", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		noticeDialog = builder.create();

		noticeDialog.show();

	}

	/**
	 * 显示下载对话框
	 */
	protected void showDownloadDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("正在下载新版本");

		final LayoutInflater inflater = LayoutInflater.from(context);

		View v = inflater.inflate(R.layout.update_progress, null);

		mProgressBar = (ProgressBar) v.findViewById(R.id.update_progress);

		mProgressText = (TextView) v.findViewById(R.id.update_progress_text);

		builder.setView(v);

		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});

		builder.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});

		downloadDialog = builder.create();

		downloadDialog.setCanceledOnTouchOutside(false);

		downloadDialog.show();

		downloadApk();
	}

	private Runnable downApkRunnbale = new Runnable() {

		@Override
		public void run() {

			try {

				String apkName = mUpdate.getVersionName() + ".apk";

				String tmpName = mUpdate.getVersionName() + ".tmp";

				// 判断是否挂载了SD卡
				String storageState = Environment.getExternalStorageState();

				if (storageState.equals(Environment.MEDIA_MOUNTED)) {
					savePath = Environment.getExternalStorageDirectory()
							.getAbsolutePath() + "/qingyang/Update";
					File file = new File(savePath);
					if (!file.exists()) {
						file.mkdir();
					}

					apkFilePath = savePath + "/" + apkName;

					tempFilePath = savePath + "/" + tmpName;
				}

				if (apkFilePath == null || apkFilePath.equals("")) {
					mHandler.sendEmptyMessage(DOWN_NOSDCARD);
					return;
				}

				File apkFile = new File(apkFilePath);

				// 如果已经存在更新文件
				if (apkFile.exists()) {
					downloadDialog.dismiss();
					downloadDialog = null;
					installApk();
					return;
				}

				File tmpFile = new File(tempFilePath);

				FileOutputStream fos = new FileOutputStream(tmpFile);

				URL url = new URL(apkUrl);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();

				conn.connect();

				int length = conn.getContentLength();

				InputStream is = conn.getInputStream();

				DecimalFormat df = new DecimalFormat("0.00");

				apkFileSize = df.format((float) length / 1024 / 1024) + "MB";

				int count = 0;

				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);

					count += numread;
					// 当先下载文件大小
					tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";

					// 当前进度值
					progress = (int) (((float) count / length) * 100);

					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);

					if (numread <= 0) {
						// 下载完成-奖临时下载文件装成APK文件
						if (tmpFile.renameTo(apkFile)) {
							// 通知安装
							mHandler.sendEmptyMessage(DOWN_OVER);
						}
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载

				fos.close();
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	};

	/**
	 * 下载apk
	 */
	private void downloadApk() {
		downLoadThread = new Thread(downApkRunnbale);
		downLoadThread.start();
	}

	/**
	 * 安装apk
	 */
	private void installApk() {
		File apkFile = new File(apkFilePath);

		if (!apkFile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkFile.toString()),
				"application/vnd.android.package-archive");
		context.startActivity(i);
	}
} public class CenterFragment extends BaseFragment implements OnClickListener,
		onKeyDownListener {

	public static final String DISK_PATH = "disk_path";

	private ListView listView;

	private ImageButton returnBtn, upBtn;

	private TextView titleView;

	private FileAdapter fileAdapter;

	private List<PcFile> fileList;

	private String diskPath;

	private MainActivity activity;

	// path的堆栈
	private static Stack<String> pathStack;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		diskPath = getArguments().getString(DISK_PATH);
		activity = (MainActivity) getActivity();
		addPath(diskPath);
	}

	/**
	 * 添加路径到堆栈
	 * 
	 * @param path
	 */
	public void addPath(String path) {

		if (pathStack == null) {
			pathStack = new Stack<String>();
		}

		pathStack.add(path);
	}

	/**
	 * 获取堆栈最上层的路径
	 * 
	 * @return
	 */
	public String getLastPath() {
		return pathStack.lastElement();
	}

	/**
	 * 移除堆栈最上层路径
	 */
	public void removeLastPath() {
		pathStack.remove(getLastPath());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.center_fragment, container,
				false);

		listView = (ListView) rootView.findViewById(R.id.center_drawer);

		fileAdapter = new FileAdapter(getActivity());

		listView.setAdapter(fileAdapter);

		listView.setOnItemClickListener(new DrawerItemClickListener());

		returnBtn = (ImageButton) rootView.findViewById(R.id.center_return_btn);

		upBtn = (ImageButton) rootView.findViewById(R.id.center_up_btn);

		returnBtn.setOnClickListener(this);

		upBtn.setOnClickListener(this);

		titleView = (TextView) rootView.findViewById(R.id.center_title);

		titleView.setText(diskPath);

		searchViewData(diskPath);

		return rootView;
	}

	/**
	 * 查询调用方法
	 */
	public void searchData(String path) {
		searchViewData(path);
		titleView.setText(path);
	}

	/**
	 * 查询view的数据
	 */
	public void searchViewData(final String path) {

		activity.putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {

				try {
					fileList = SocketClient.getFileInfo(getMyApplication(),
							path);
				} catch (AppException e) {
					return false;
				}

				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);

				if (result) {

					fileAdapter.setList(fileList);

					fileAdapter.setSelectedPosition(-1);

					fileAdapter.notifyDataSetChanged();

				} else {
					UIHelper.ToastMessage(activity, R.string.msg_search_error);
				}
			}
		});
	}

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			fileAdapter.setSelectedPosition(position);

			selectItem(position);
		}
	}

	private void selectItem(int position) {

		String filePath = fileAdapter.getList().get(position).getFilePath();

		String fileName = fileAdapter.getList().get(position).getFileName();

		if (fileAdapter.getList().get(position).isDirectory()) {
			searchData(filePath);
			addPath(filePath);
		} else if (fileAdapter.getList().get(position).isFile()) {

			Bundle args = new Bundle();

			args.putString(DownLoadActivity.FILE_NAME, fileName);

			args.putString(DownLoadActivity.FILE_PATH, filePath);

			Intent intent = new Intent(getActivity(), DownLoadActivity.class);

			intent.putExtras(args);

			getActivity().startActivity(intent);
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.center_return_btn:
			if (getLastPath().equals(diskPath)) {
				return;
			}
			removeLastPath();

			searchData(getLastPath());

			break;

		case R.id.center_up_btn:
			Intent intent = new Intent(activity, LocalFileDialog.class);
			intent.putExtra(UploadActivity.SAVE_PATH, getLastPath());
			activity.startActivity(intent);
			break;
		}
	}

	@Override
	public void fragmentKeyDown(int keyCode, KeyEvent event) {

		if (getLastPath().equals(diskPath)) {
			final CustomDialog outdialog = new CustomDialog(activity,
					activity.getCurrentFocus());

			outdialog.setTitle("提示");
			outdialog.setMessage("确定退出?");
			outdialog.setPositiveButton("确定", new OnClickListener() {
				@Override
				public void onClick(View v) {
					outdialog.dismiss();
					AppManager.getAppManager().AppExit(activity);
				}
			});
			outdialog.setNegativeButton("取消", new OnClickListener() {
				@Override
				public void onClick(View v) {
					outdialog.dismiss();
				}
			});
			outdialog.show();
			return;
		}
		removeLastPath();

		searchData(getLastPath());
	}

} public class SocketClient {

	// 连接超时时间
	private static final int TIMEOUT_CONNECTION = 2000;

	// 重新操作次数
	private static final int RETRY_TIME = 3;

	/**
	 * 获取socket
	 * 
	 * @return
	 * @throws IOException
	 * @throws UnknownHostException
	 * @throws Exception
	 */
	private static Socket getSocket(BaseApplication application)
			throws UnknownHostException, IOException {
		Socket socket = new Socket(application.getIpAdress(), URL.PC_PORT);
		socket.setKeepAlive(true);
		socket.setSoTimeout(TIMEOUT_CONNECTION);
		return socket;
	}

	/**
	 * socket连接方法
	 * 
	 * @return
	 */
	private static String socketConnect(BaseApplication application,
			String method) throws AppException {

		DataInputStream dis = null;

		DataOutputStream dos = null;

		Socket socket = null;

		String result = "";

		int time = 0;

		do {
			try {
				socket = getSocket(application);

				dos = new DataOutputStream(socket.getOutputStream());

				dos.writeUTF(method);

				dis = new DataInputStream(socket.getInputStream());

				result = dis.readUTF();
				break;

			} catch (IOException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);

						continue;
					} catch (InterruptedException e1) {
					}
				}
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				try {
					if (dis != null) {
						dis.close();
					}
					if (dos != null) {
						dos.close();
					}
					if (socket != null) {
						socket.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
					throw AppException.network(e);
				}

			}
		} while (time < RETRY_TIME);

		return result;
	}

	// 获取盘符信息
	public static List<Disk> getDiskInfo(BaseApplication application)
			throws AppException {
		return Disk.parse(socketConnect(application, URL.GET_DISK));
	}

	// 获取盘符下的文件信息
	public static List<PcFile> getFileInfo(BaseApplication application,
			String diskPath) throws AppException {
		return PcFile.parse(socketConnect(application, diskPath));
	}

	// 关闭PC计算机
	public static boolean PowerOffPc(BaseApplication application)
			throws AppException {
		return Boolean.valueOf(socketConnect(application, URL.POWER_PC));
	}

	// 控制鼠标
	public static boolean mouseControl(BaseApplication application, String msg)
			throws AppException {
		return Boolean.valueOf(socketConnect(application, msg));
	}
} public class CustomDialog {

	private View mParent;

	private PopupWindow popupWindow;

	private LinearLayout mRootLayout;

	private LayoutParams layoutParams;

	// popupwindow 必须有一个parentView,所以必须加这个参数
	public CustomDialog(Context context, View parent) {
		this.mParent = parent;

		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		// 加载布局文件
		mRootLayout = (LinearLayout) layoutInflater.inflate(
				R.layout.custom_dialog, null);

		layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
				layoutParams.WRAP_CONTENT);
	}

	/**
	 * 设置dialog的标题
	 * 
	 * @param title
	 */
	public void setTitle(String title) {
		TextView mTitle = (TextView) mRootLayout
				.findViewById(R.id.custom_dialog_title);

		mTitle.setText(title);
	}

	/**
	 * 设置dialog的主体内容
	 * 
	 * @param title
	 */
	public void setMessage(String message) {
		TextView mMessage = (TextView) mRootLayout
				.findViewById(R.id.custom_dialog_content_text);

		mMessage.setText(message);
	}

	/**
	 * 设置dialog的确定按钮
	 */
	public void setPositiveButton(String text, OnClickListener onClickListener) {
		final Button buttonOk = (Button) mRootLayout
				.findViewById(R.id.custom_dialog_btn_ok);
		buttonOk.setText(text);
		buttonOk.setOnClickListener(onClickListener);
		buttonOk.setVisibility(View.VISIBLE);
	}

	/**
	 * 设置dialog的取消按钮
	 */
	public void setNegativeButton(String text, OnClickListener onClickListener) {
		final Button buttonCancel = (Button) mRootLayout
				.findViewById(R.id.custom_dialog_btn_cancel);
		buttonCancel.setText(text);
		buttonCancel.setOnClickListener(onClickListener);
		buttonCancel.setVisibility(View.VISIBLE);
	}

	/**
	 * 替换dialog的主体布局
	 * 
	 * @param layout
	 */
	public void setContentLayout(View layout) {
		TextView message = (TextView) mRootLayout
				.findViewById(R.id.custom_dialog_content_text);
		message.setVisibility(View.GONE);
		LinearLayout contentLayout = (LinearLayout) mRootLayout
				.findViewById(R.id.custom_dialog_contentview);
		contentLayout.addView(layout);
	}

	/**
	 * 设置dialog的长宽
	 * 
	 * @param width
	 * @param height
	 */
	public void setLayoutParams(int width, int height) {
		layoutParams.width = width;
		layoutParams.height = height;
	}

	/**
	 * 显示dialog
	 */
	public void show() {
		if (popupWindow == null) {
			popupWindow = new PopupWindow(mRootLayout, layoutParams.width,
					layoutParams.height);
			popupWindow.setFocusable(true);
		}
		popupWindow.showAtLocation(mParent, Gravity.CENTER, Gravity.CENTER,
				Gravity.CENTER);
	}

	/**
	 * 取消dialog的显示
	 */
	public void dismiss() {
		if (popupWindow == null) {
			return;
		}
		popupWindow.dismiss();
	}
}
import java.util.List;
import com.example.qingyangdemo.adapter.DiskAdapter;
import com.example.qingyangdemo.base.AppException;
import com.example.qingyangdemo.base.AppManager;
import com.example.qingyangdemo.base.BaseActivity;
import com.example.qingyangdemo.bean.Disk;
import com.example.qingyangdemo.common.UIHelper;
import com.example.qingyangdemo.common.UpdateManager;
import com.example.qingyangdemo.fragment.CenterFragment;
import com.example.qingyangdemo.net.SocketClient;
import com.example.qingyangdemo.ui.CustomDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.AdapterView.OnItemClickListener;
		public void onDrawerStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		// 打开/关闭抽屉
		case R.id.open_llt:
			if (mDrawerLayout.isDrawerOpen(left_drawer_LinearLayout)) {
				mDrawerLayout.closeDrawer(left_drawer_LinearLayout);
			} else {
				mDrawerLayout.openDrawer(Gravity.LEFT);
			}
			break;

		// 菜单按钮
		case R.id.fragment_menu:
			int x = 0;
			int y = 0;

			if (!application.isTablet()) {
				x = screenWidth - v.getRight() + 20;
				y = v.getBottom() + 60;
			} else {
				x = screenWidth - v.getRight() + 10;
				y = v.getBottom() + 10;
			}

			showPopMenu(x, y);
			break;
		}
	}

	/**
	 * 显示菜单
	 * 
	 * @param x
	 * @param y
	 */
	public void showPopMenu(int x, int y) {
		LinearLayout layout = (LinearLayout) LayoutInflater.from(
				MainActivity.this).inflate(R.layout.pop_menu, null);
		ListView listView = (ListView) layout.findViewById(R.id.menu_list);
		listView.setAdapter(new ArrayAdapter<String>(MainActivity.this,
				R.layout.pop_menu_item, R.id.tv_text, title));

		popupWindow = new PopupWindow(MainActivity.this);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		if (application.isTablet()) {
			popupWindow.setWidth(screenWidth / 4);
		} else {
			popupWindow.setWidth(screenWidth / 3);
		}
		popupWindow.setHeight(LayoutParams.WRAP_CONTENT);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.setContentView(layout);
		// 需要指定Gravity，默认情况是center
		popupWindow.showAtLocation(view, Gravity.RIGHT | Gravity.TOP, x, y);
		listView.setOnItemClickListener(new MenuItemClick());
	}

	/**
	 * 菜单每项点击事件
	 * 
	 * @author R21
	 * 
	 */
	private class MenuItemClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			switch (position) {
			case 0:
				UIHelper.showLoginDialog(MainActivity.this);
				break;
			case 1:
				final CustomDialog dialog = new CustomDialog(MainActivity.this,
						getCurrentFocus());

				dialog.setTitle("提示");
				dialog.setMessage("确定注销登录?");
				dialog.setPositiveButton("确定", new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.setNegativeButton("取消", new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.show();
				break;
			case 2:
				startActivity(SettingActivity.class);
				break;
			case 3:
				startActivity(ControlMouseActivity.class);
				break;
			case 4:
				startActivity(PowerOffActivity.class);
				break;
			case 5:
				final CustomDialog outdialog = new CustomDialog(
						MainActivity.this, getCurrentFocus());

				outdialog.setTitle("提示");
				outdialog.setMessage("确定退出?");
				outdialog.setPositiveButton("确定", new OnClickListener() {
					@Override
					public void onClick(View v) {
						outdialog.dismiss();
						AppManager.getAppManager().AppExit(MainActivity.this);