1. 程式人生 > >Looper.prepare()和Looper.loop(),在子執行緒中更新UI

Looper.prepare()和Looper.loop(),在子執行緒中更新UI

當子執行緒想直接更新UI時,例如進行Toast提示。

可以先Looper.prepare(),然後Looper.loop(),程式碼如下(加黑處):

public class CrashHandler implements UncaughtExceptionHandler {
	TApplication tApplication;

	public CrashHandler(TApplication tApplication) {
		super();
		this.tApplication = tApplication;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		StringWriter stringWriter = new StringWriter();
		PrintWriter printWriter = new PrintWriter(stringWriter);
		ex.printStackTrace(printWriter);
		String string = stringWriter.toString();
		Log.i("tedu1", "出錯了4 " + string);
		// 啟工作執行緒,toast是介面控制元件
		// 工作執行緒不能更新UI
		<strong>new Thread() {
			public void run() {
				// show用到佇列 主執行緒有looper,取訊息放佇列
				Looper.prepare();
				Toast.makeText(tApplication, "網路不穩定,程式即將重啟", Toast.LENGTH_SHORT).show();
				Looper.loop();

			};
		}.start();
</strong>
		try {
			Thread.currentThread().sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Intent intent = new Intent(tApplication, MainActivity.class);
		// 不執行
		PendingIntent pendingIntent = PendingIntent.getActivity(tApplication, 100, intent,
				Intent.FLAG_ACTIVITY_NEW_TASK);

		// 過一會執行pendingIntent
		AlarmManager alarmManager = (AlarmManager) tApplication.getSystemService(Context.ALARM_SERVICE);
		alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 200, pendingIntent);
		tApplication.finish();

	}

}

程式碼出自跑跑專案。