【问题标题】:Layout is hanged during asynctask in android在android中的asynctask期间布局被挂起
【发布时间】:2013-02-19 04:44:57
【问题描述】:

我是安卓开发新手。 我正在尝试加载一些我想异步执行的网络数据,以便在网络操作完成之前显示启动画面。现在,当我运行 belo 时,启动画面不会显示,而是显示一个带有标题栏的空白屏幕挂起状态。

我也在清单文件中将此活动标记为 LAUNCHER。你能告诉我什么是正确的方法吗?

这是我的初始屏幕代码。

public class SplashScreen extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);

            try{

                        AsyncTask<Void, Void, HukumNamaDetails> async=new URLReader(splashScreen).execute();
                        hdetails=async.get();

                        splashScreen.saveImage(currdate);


                    }

         catch(InterruptedException e) {} catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally {
                System.out.println("In finally");
                finish();

                //start a new activity
                Intent i = new Intent();
                i.putExtra("hdetails", new HukumNamaDetails(hdetails.getHukumnama_punjabi()
                    ,hdetails.getPunjabi_vyakhya(),hdetails.getEnglish_translation()));
                i.setClass(splashScreen, Daily_HukumNama.class);
                startActivity(i);
            }
        }

//Function that will handle the touch
@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        synchronized(splashTread){
                splashTread.notifyAll();
        }
    }
    return true;
}


}

谢谢 阿曼迪普

【问题讨论】:

  • 因为您正在调用 AsyncTask.get(),这使得 UI 线程等到 doInBackground 执行未完成

标签: android android-asynctask splash-screen


【解决方案1】:

使用 AsyncTask 可能有点冒险:

1. 使用 AsyncTask 的 onPreExecute()启动 启动画面

2. 在 AsyncTask 的 doInBackground() 中完成你的工作不要在此处尝试任何 UI 内容

3. *删除* AsyncTask 的 onPostExecute() 中的 splash 屏幕作为您的背景内容到时候搞定。

要启动 AsyncTask,只需使用 AsyncTask 对象的引用调用 execute()。

注意:在我看来,此时调用 get() 是不必要的。

【讨论】:

    【解决方案2】:

    调用get() 函数将导致您的UI 线程等待计算完成。不要调用get() 方法。而是在AsyncTaskonPostExecute() 方法中进行所有后处理。

    【讨论】:

      【解决方案3】:

      https://developer.android.com/reference/android/os/AsyncTask.html

      不要打电话给get()。在您的 AsyncTask 中覆盖 onPostExecute() 以处理操作导致的任何 UI 更新。调用get()会导致UI线程阻塞。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-15
        • 1970-01-01
        相关资源
        最近更新 更多