android_线程使用示例

// ---------------后台线程,获取通知用的-----------------------//
static boolean m_stop = false;
static int m_maxNotifyID;
static MainHandler m_handler;

static class BarcodeReadThread extends Thread {
	public void run() {
		while (!m_stop) {
			try {
				Thread.sleep(30000);// 30秒查询一次
				JSONArray jsonParam = new JSONArray();
				jsonParam.put(m_maxNotifyID + "");
				String result = HKNet.excuteTaskByLabel("Other_GetNotify",
						jsonParam);

				Message msg = new Message();
				msg.what = 200;
				msg.obj = result;
				m_handler.sendMessage(msg);

			} catch (InterruptedException e) {
				// 忽略所有的错误
				e.printStackTrace();
			}
		}
	};
}

private static class MainHandler extends Handler {
	private final WeakReference<MainActivity> weakReference;
	MainActivity activity;

	public MainHandler(MainActivity activity) {
		weakReference = new WeakReference<MainActivity>(activity);
		this.activity = weakReference.get();
	}

	@Override
	public void handleMessage(Message msg) {
		switch (msg.what) {
		case 200: {
			String result = (String) msg.obj;
			try {
				JSONObject jsonObj = new JSONObject(result);
				if (HKNet.isNetWorkSuccess(jsonObj)) {
					JSONArray jsonArr = jsonObj
							.getJSONArray(Config.Str.List);
					DataTable dt = new DataTable(jsonArr);
					if (dt.haveData()) {
						// 插入记录到通知表,标记最新的一笔为未读
						activity.daoNotify.insert(dt);
						// 更新maxNotifyID
						m_maxNotifyID = activity.daoNotify.getMaxNofityID();
						// 弹出新通知

					} else {
						// 没有最新的通知
					}
				} else {
					// 忽略错误
					// String msg = HKNet.getMsg(jsonObj);
				}
			} catch (JSONException e) {
				// 忽略错误
				// activity.toast("解析数据失败:" + e.toString());
				System.out.println("解析数据失败:" + e.toString() + "\n result:"
						+ result);
			}
			break;
		}
		}
	}
}

你可能感兴趣的:(android)