我有一个启动画面的 Activity ,它在布局中只有一个图像。当初始屏幕显示在 UI 线程中时,我想在后台进行一些 Http 调用。但是当我执行 AsyncTask 时,布局中的图像不会显示。我只得到一个空白屏幕,让我相信布局本身没有加载。以下是 Activity 代码。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
String authReqResponse;
Toast errorDisplayToast = new Toast(this);
AuthorizationRequest authReq = new AuthorizationRequest();
authReq.execute(new Void[] {});
try {
authReqResponse = authReq.get();
if(authReqResponse.equalsIgnoreCase(GeneralConstants.AUTH_FAILED_ERROR)) {
errorDisplayToast.makeText(SplashScreen.this, R.string.request_auth_failed_error_message, Toast.LENGTH_LONG);
errorDisplayToast.show();
} else if(authReqResponse.equalsIgnoreCase(null)) {
errorDisplayToast.makeText(SplashScreen.this, R.string.networkErrorMessage, Toast.LENGTH_LONG);
errorDisplayToast.show();
} else {
GeneralConstants.REQ_TOKEN = authReqResponse;
Intent startARIntent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(startARIntent);
finish();
}
} catch(Exception e) {
e.printStackTrace();
}
}
最佳答案
这里
try {
authReqResponse = authReq.get();///<<get method of AsyncTask
//your code....
关于 AsyncTask. get (long timeout, TimeUnit unit) : 的文档
Waits if necessary for at most the given time for the computation to complete, and then retrieves its result.
意味着如果您使用此方法将结果从 AsyncTask 返回到您的 UI 主线程,那么它将停止您的主 UI 执行,直到结果未从 AsyncTask 的 doInBackground 方法返回
解决方案是在 AsyncTask 执行完成时使用 onPostExecute
更新 UI 元素
关于android - 运行 AsyncTask 时不显示布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999973/