Looper.prepare()和Looper.loop(),在子线程中更新UI
2016-05-02 17:07
363 查看
当子线程想直接更新UI时,例如进行Toast提示。
可以先Looper.prepare(),然后Looper.loop(),代码如下(加黑处):
代码出自跑跑项目。
可以先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(); } }
代码出自跑跑项目。
相关文章推荐
- C#实现窗体与子线程的交互的方法
- C#在子线程中更新窗口部件的写法
- android的消息处理机制(图文+源码分析)―Looper/Handler/Message
- Android中的Looper对象详细介绍
- Android消息处理机制Looper和Handler详解
- AsyncTask陷阱之:Handler,Looper与MessageQueue的详解
- android开发教程之子线程中更新界面
- Android中子线程和UI线程通信详解
- 子线程更新UI(非Handle)
- 实现死锁的两种方式以及ReentrantLock的额外功能(未完待续)
- android之AsncTask异步任务使用
- UI线程、子线程 以及子线程间的通信
- Looper类浅析
- Android的线程使用来更新UI----Thread、Handler、Looper、Time...
- Handler Looper MessageQueue总结
- Android多线程Handler的使用,基于源代码理解。
- Android之Looper+Thread+handler
- 单线程模型中Message、Handler、Message Queue、Looper之间的关系。
- 最近学习qt,一些细节备忘
- Android的Looper和Handler消息处理机制详解