您的位置:首页 > 产品设计 > UI/UE

Looper.prepare()和Looper.loop(),在子线程中更新UI

2016-05-02 17:07 363 查看
当子线程想直接更新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();

}

}


代码出自跑跑项目。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Looper 子线程