从线程处理UI code [英] Handling UI code from a Thread

查看:113
本文介绍了从线程处理UI code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用处理程序更新UI元素,例如等待进度条吐司等。

我遇到的问题是当背景消失,如用户pressing后退按钮或活动结束的某些原因。这使我的应用程序经常崩溃。

我试着用getApplicationContext()(思考,这将是在我的整个应用程序提供),但没有工作,永远! - 而不是我的应用程序崩溃。

我把周围的尝试所有的UI更新code catch块,这工作,但有必要吗?

所以...什么是处理这个问题的方式韧皮?


解决方案

  

我遇到的问题是当
  上下文消失,例如用户
  pressing后退按钮或
  活动结束出于某种原因。
  这使我的应用程序崩溃
  常。


您也将获得该默认情况下,如果用户更改屏幕方向,因为原来的活动被破坏,一个新的创造。


  

我试着用getApplicationContext()
  (思考,这将是可用
  在我的整个应用程序),但
  这个没有工作,不断 - 不是我
  应用程序崩溃!


应用程序上下文是操纵UI的角度看无用的。


  

所以...什么是处理这个问题的方式韧皮?


在最后,你需要的是你的线程提供一个事件到正确的活动。人们已经使用的一些技巧包括:


  • 使用侦听器模式(例如,服务管理线程,活动注册和注销服务听众,线程调用关键事件监听器)

  • 把活动的当前比如在一个静态数据成员,该线程使用,以找出哪一个应使用(危险,由于内存泄漏和失败,如果您需要多个实例)

  • 限制后台线程来高速缓存数据的人,该活动拉动(例如,通过轮询)根据需要

I know how to use handlers to update UI elements such as progress bars toasts etc.

The problem I am having is when the context goes away such as the user pressing the back button or the Activity finishing for some reason. This causes my application to crash often.

I tried using getApplicationContext() (Thinking that this would be available throughout my entire application) but this did not work, ever - instead my application crashed!

I put try catch blocks around all UI update code, this works but is it necessary?

So...what is the bast way to handle this?

解决方案

The problem I am having is when the context goes away such as the user pressing the back button or the Activity finishing for some reason. This causes my application to crash often.

You will also get this, by default, if the user changes screen orientation, as the original activity is destroyed and a new one created.

I tried using getApplicationContext() (Thinking that this would be available throughout my entire application) but this did not work, ever - instead my application crashed!

The application context is useless from the standpoint of manipulating the UI.

So...what is the bast way to handle this?

In the end, what you need is for your thread to deliver an event to the right activity. Some techniques that people have used include:

  • Use a listener pattern (e.g., service manages the thread, activities register and unregister listeners with the service, thread invokes the listeners on key events)
  • Put the "current" instance of the activity in a static data member, which the thread uses to find out which one should be used (dangerous due to memory leaks and fails if you need multiple instances)
  • Limit background threads to ones that cache data, which the activity pulls (e.g., via polling) as needed

这篇关于从线程处理UI code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆