首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

一个关于Dialog内的UI线程的使用有关问题

2012-09-23 
一个关于Dialog内的UI线程的使用问题在Dialog.java类中,有几行代码是关乎UI线程的操作的,拿出来研究一下,

一个关于Dialog内的UI线程的使用问题

在Dialog.java类中,有几行代码是关乎UI线程的操作的,拿出来研究一下,呵呵

?

private final Thread mUiThread;

private final Handler mHandler = new Handler();// 只在下面用了一次而已

private final Runnable mDismissAction = new Runnable() {
??????? public void run() {
??????????? dismissDialog();
??????? }
??? };

?

/**
?* Dismiss this dialog, removing it from the screen. This method can be
?* invoked safely from any thread.? Note that you should not override this
?* method to do cleanup when the dialog is dismissed, instead implement
?* that in {@link #onStop}.
?*/

public void dismiss() {
??????? if (Thread.currentThread() != mUiThread) {
??????????? mHandler.post(mDismissAction);
??????? } else {
??????????? mDismissAction.run();
??????? }
??? }

?

/**
???? * Create a Dialog window that uses a custom dialog style.
???? *
???? * @param context The Context in which the Dialog should run. In particular, it
???? *??????????????? uses the window manager and theme from this context to
???? *??????????????? present its UI.
???? * @param theme A style resource describing the theme to use for the
???? * window. See <a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">Style
???? * and Theme Resources</a> for more information about defining and using
???? * styles.? This theme is applied on top of the current theme in
???? * <var>context</var>.? If 0, the default dialog theme will be used.
???? */
??? public Dialog(Context context, int theme) {
??????? mContext = new ContextThemeWrapper(
??????????? context, theme == 0 ? com.android.internal.R.style.Theme_Dialog : theme);
??????? mWindowManager = (WindowManager)context.getSystemService("window");
??????? Window w = PolicyManager.makeNewWindow(mContext);
??????? mWindow = w;
??????? w.setCallback(this);
??????? w.setWindowManager(mWindowManager, null, null);
??????? w.setGravity(Gravity.CENTER);
??????? mUiThread = Thread.currentThread();
??????? mListenersHandler = new ListenersHandler(this);
??? }

?

我猜想,这个像对话框这种控件是只允许在UI主线程内操作的,也就是说只能由UI主线程来控制显示或消失等等,

那么有些对话框不依赖于Activity也就不容易找到UI主线程,所以就得需要把它的新线程的操作并入UI主线程中去完成,

也就是mHandler.post(mDismissAction);

?

那么主线程从哪来的呢?就在Dialog的构造里找到的,mUiThread = Thread.currentThread();

这依赖于制造这个Dialog的地方的性质。

?

只是我的猜想,如果有人觉得可以再分析一下,欢迎讨论,敬请指教,谢啦

热点排行