在异步任务时显示加载屏幕

时间:2013-01-24 09:23:26

标签: android android-asynctask

我有这个异步任务,调用Web服务并解析xml

@Override
protected void onPreExecute(){
super.onPreExecute();
time = System.currentTimeMillis();
}
 protected Boolean doInBackground(Integer... params) {
  //code 
 }

protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
    difftime = System.currentTimeMillis() - time;
 }

当异步任务正在执行时我想显示一个加载屏幕,但是如果我这样做的话,加载屏幕在异步任务完成之前完成

        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading_screen);

            final CallWebService callTarif = new CallWebService(6,sett.getDeviceId());
            callTarif.execute();

new Handler().postDelayed(new Runnable(){ 
        @Override 
            public void run() { 

                LoadingScreen.this.finish(); 
                Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
                                    startActivity(intent);            
            } 

        }
        },callTarif.difftime);

3 个答案:

答案 0 :(得分:0)

在完成 AsyncTask 之前,实际上会调用postDelayed

只需输入这些代码行

即可
LoadingScreen.this.finish(); 
Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
startActivity(intent);     

在AsyncTask的opPostExecute()中。

protected void onPostExecute(Boolean result) {
super.onPostExecute(result);

    difftime = System.currentTimeMillis() - time;
    LoadingScreen.this.finish(); 
    Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
    startActivity(intent);      
}

并移除处理程序 new Handler().postDelayed(new Runnable(){

答案 1 :(得分:0)

启动加载屏幕onPreExecute方法并将其杀死onPostExecute方法的异步任务

答案 2 :(得分:0)

使用异步任务访问webservice时,无需使用Handler显示加载。使用AsyncTask的onPreExecute()方法显示加载屏幕并在onPostExecute内完成,因为此方法在doInBackground执行完成时调用。将代码更改为:

      @Override
      protected void onPreExecute() {
            // show loading bar here
      }
@Override
      protected String doInBackground(String... params) {
                 // do network operation here
            return null;
      }      

      @Override
      protected void onPostExecute(String result) {      
          // dismiss loading bar here         
      }