我决定显示对话框与消息"授权"当我的应用程序检索授权令牌谷歌帐户从帐户管理器,然后我要更新对话框设置消息"保存联系人",并在这个时候执行保存联系人的长操作,但当我试图使这像下面的代码我的auth对话框不显示(它需要8秒的黑屏,然后对话框出现一秒钟和辞退)。我在处理程序线程中创建和更新对话框,这是绑定到UI线程(在onCreate方法中创建处理程序)。当我创建对话框时,它看起来像UI线程阻塞。这是我的代码:
public void gotAccount(final GoogleAccountManager googleAccountManager,
final Account account)
{
SharedPreferences settings = getSharedPreferences(PREF, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accountName", account.name);
editor.commit();
Log.i("gotAccount","start new thread");
new Thread(new Runnable()
{
public void run()
{
Log.i("gotAccount-Thread run()","start show loading message");
createLoadingMessage();
Log.i("gotAccount-Thread run()","complete show loading message");
Log.i("gotAccount-Thread run()","start getAuthToken");
googleAccountManager.manager
.getAuthToken(account, AUTH_TOKEN_TYPE, true, new AccountManagerCallback<Bundle>()
{
@Override
public void run(AccountManagerFuture<Bundle> future)
{
try
{
Log.i("gotAccount-run()","get auth token complete");
Log.i("callback-run()","start get result");
Bundle bundle = future.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT))
{
Intent intent = bundle
.getParcelable(AccountManager.KEY_INTENT);
int flags = intent.getFlags();
flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
intent.setFlags(flags);
startActivityForResult(intent, REQUEST_AUTHENTICATE);
} else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN))
{
createSaveContactsMessage();
setAuthToken(bundle
.getString(AccountManager.KEY_AUTHTOKEN));
longOperation();
completeSave(getText(R.string.saved) + ": "
+ currentCount);
}
} catch (Exception e)
{
handleException(e);
}
}
},null);
}
}).start();
}
有一种更简单的方法来处理线程。例如AsyncTask,你在preExecute()中定义你的进度条,在doInBackground()中做需要做的事情,并在onPostExecute()中删除对话框。
关于异步任务的更多信息