【发布时间】:2013-07-24 10:40:18
【问题描述】:
我是Android 的初学者,我对Android UI Thread 有一些困惑。现在,我知道除了创建 UI 的线程之外,没有其他线程可以修改它。
太棒了。
这是我的第一个 Android 应用程序中的Activity,这让我有点困惑。
public class NasaDailyImage extends Activity{
public ProgressDialog modalDialog = null;
//------------------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState){
//Instantiate progress dialog, skipping details.
Button b = //get reference to button
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
modalDialog.show(); // show modal
Toast.makeText(getApplicationContext(), "Getting feeds", 500).show();
new AsyncRetriever().execute(new IotdHandler()); // Get the feeds !!
}
});
}
//------------------------------------------------------------------------------
public synchronized void resetDisplay(boolean parseErrorOccured,
boolean imageErrorOccured,
IotdHandler newFeeds){
if(parseErrorOccured || imageErrorOccured){
// make a Toast
// do not update display
}else{
// make a Toast
// update display
// based on new feed
}
}
//------------------------------------------------------------------------------
class AsyncRetriever extends AsyncTask<IotdHandler,Void,IotdHandler>{
@Override
protected IotdHandler doInBackground(IotdHandler... arg0) {
IotdHandler handler = arg0[0];
handler.processFeed(); // get the RSS feed data !
return handler;
}
//------------------------------------------------------------------------------
@Override
protected void onPostExecute(IotdHandler fromInBackground){
resetDisplay( // call to update the display
fromInBackground.errorOccured,
fromInBackground.imageError,
fromInBackground);
}
//------------------------------------------------------------------------------
}
1.
onCreate 在 UI 线程上,所以我可以做任何我想做的事情,但 onClick 不是。 为什么我可以在那个方法中创建 ProgressDialog 和 Toast? 为什么没有错误?2.
AsyncTask 是NasaDailyImage 的子类。这意味着它可以访问所有 NasaDailyImage 的方法,包括更新显示的resetDisplay()。 resetDisplay() 在 onPostExecute 中被调用,它在与 UI 不同的线程上运行。那么,为什么我可以在那里更新显示却没有错误?
【问题讨论】:
-
onClick和onPostExecute都在 UI 线程上运行。您的代码中唯一没有的是doInBackground,顾名思义,它在后台线程上运行。 -
@Geobits AFAIK,这与在 不同线程 上处理事件的旧 Java 不同,对吗? UI 是一个线程,事件处理在另一个线程上
-
在 Android 中,一切都在 UI 线程中运行,除非您创建线程或使用使用线程的框架类。
标签: android concurrency android-asynctask ui-thread