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;}@Overridepublic 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 blocke.printStackTrace();}Intent intent = new Intent(tApplication, MainActivity.class);// 不执行PendingIntent pendingIntent = PendingIntent.getActivity(tApplication, 100, intent,Intent.FLAG_ACTIVITY_NEW_TASK);// 过一会执行pendingIntentAlarmManager alarmManager = (AlarmManager) tApplication.getSystemService(Context.ALARM_SERVICE);alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 200, pendingIntent);tApplication.finish();}}
代码出自跑跑项目。