65

我试图在从 HTTP 服务器加载 RSS 提要时显示自定义进度对话框,我进行了艰苦的搜索,但没有任何帮助我做到这一点,我唯一知道的是解决方案应该使用AsyncTask,但我很困惑传递给 this 的参数AsyncTask。这是我的活动:

public class Soirees extends ListActivity {

    private List<Message> messages;
    private TextView tvSorties;
    private MyProgressDialog dialog;

    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);
        setContentView(R.layout.sorties);

        tvSorties=(TextView)findViewById(R.id.TVTitle);
        tvSorties.setText("Programme des soirées");

        loadFeed();

    }

    private void loadFeed(){

        try{
            BaseFeedParser parser = new BaseFeedParser();
            messages = parser.parse();
            List<Message> titles = new ArrayList<Message>(messages.size());
            for (Message msg : messages){
                titles.add(msg);
            }
            MessageListAdapter adapter = new MessageListAdapter(this,titles);
            this.setListAdapter(adapter);
            adapter.notifyDataSetChanged();

        } catch (Throwable t){
            Log.e("ImageLoader",t.getMessage(),t);
        }
    }

}

你能帮我补充AsyncTask一下吗?

4

7 回答 7

128
/**
 * this class performs all the work, shows dialog before the work and dismiss it after
 */
public class ProgressTask extends AsyncTask<String, Void, Boolean> {

    public ProgressTask(ListActivity activity) {
        this.activity = activity;
        dialog = new ProgressDialog(activity);
    }

    /** progress dialog to show user that the backup is processing. */
    private ProgressDialog dialog;
    /** application context. */
    private ListActivity activity;

    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

        @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }


        MessageListAdapter adapter = new MessageListAdapter(activity, titles);
        setListAdapter(adapter);
        adapter.notifyDataSetChanged();


        if (success) {
            Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
        }
    }

    protected Boolean doInBackground(final String... args) {
       try{    
          BaseFeedParser parser = new BaseFeedParser();
          messages = parser.parse();
          List<Message> titles = new ArrayList<Message>(messages.size());
          for (Message msg : messages){
              titles.add(msg);
          }
          activity.setMessages(titles);
          return true;
       } catch (Exception e)
          Log.e("tag", "error", e);
          return false;
       }
    }
}

public class Soirees extends ListActivity {
    private List<Message> messages;
    private TextView tvSorties;
    private MyProgressDialog dialog;
    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        setContentView(R.layout.sorties);

        tvSorties=(TextView)findViewById(R.id.TVTitle);
        tvSorties.setText("Programme des soirées");

        // just call here the task
        AsyncTask task = new ProgressTask(this).execute();
   }

   public void setMessages(List<Message> msgs) {
      messages = msgs;
   }

}
于 2010-12-27T11:30:25.770 回答
44

通过将视图修饰符移动到 onPostExecute 进行修复,因此固定代码为:

public class Soirees extends ListActivity {
    private List<Message> messages;
    private TextView tvSorties;

    //private MyProgressDialog dialog;
    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        setContentView(R.layout.sorties);

        tvSorties=(TextView)findViewById(R.id.TVTitle);
        tvSorties.setText("Programme des soirées");

        new ProgressTask(Soirees.this).execute();


   }


    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;
        List<Message> titles;
        private ListActivity activity;
        //private List<Message> messages;
        public ProgressTask(ListActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }



        /** progress dialog to show user that the backup is processing. */

        /** application context. */
        private Context context;

        protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }

            @Override
        protected void onPostExecute(final Boolean success) {
                List<Message> titles = new ArrayList<Message>(messages.size());
                for (Message msg : messages){
                    titles.add(msg);
                }
                MessageListAdapter adapter = new MessageListAdapter(activity, titles);
                activity.setListAdapter(adapter);
                adapter.notifyDataSetChanged();

                if (dialog.isShowing()) {
                dialog.dismiss();
            }

            if (success) {
                Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
            }
        }

        protected Boolean doInBackground(final String... args) {
            try{    
                BaseFeedParser parser = new BaseFeedParser();
                messages = parser.parse();


                return true;
             } catch (Exception e){
                Log.e("tag", "error", e);
                return false;
             }
          }


    }

}

@Vladimir,谢谢您的代码非常有帮助。

于 2010-12-27T13:18:28.273 回答
9

AsyncTask 非常有帮助!

class QueryBibleDetail extends AsyncTask<Integer, Integer, String>{
        private Activity activity;
        private ProgressDialog dialog;
        private Context context;

        public QueryBibleDetail(Activity activity){
            this.activity = activity;
            this.context = activity;
            this.dialog = new ProgressDialog(activity);
            this.dialog.setTitle("查询经文");
            this.dialog.setMessage("正在查询:"+tome+chapterID+":"+sectionFromID+"-"+sectionToID);
            if(!this.dialog.isShowing()){
                this.dialog.show();
            }
        }

        @Override
        protected String doInBackground(Integer... params) {
            Log.d(TAG,"经文doInBackground");
            publishProgress(params[0]);

            if(sectionFromID > sectionToID){
                return "";
            }

            String queryBible = "action=query_bible&article="+chapterID+"&id="+tomeID+"&verse_start="+sectionFromID+"&verse_stop="+sectionToID+"";
            try{
                String bible = (Json.getRequest(HOST+queryBible)).trim();
                bible = android.text.Html.fromHtml(bible).toString();
                return bible;
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String bible){
            Log.d(TAG,"经文onPostExecute");
            TextView bibleBox = (TextView) findViewById(R.id.bibleBox);
            bibleBox.setText(bible);
            this.dialog.dismiss();
        }
    }
于 2013-02-02T12:20:28.467 回答
3

几天前,我发现了一个非常好的解决这个问题的方法。在这里阅读。简而言之,Mike 创建了一个协调 ProgressDialog 和 AsyncTask 的 AsyncTaskManager。使用此解决方案非常容易。您只需要在您的项目中包含几个接口和几个类,并在您的活动中编写一些简单的代码并从 BaseTask 嵌套您的新 AsyncTask。我还建议您阅读评论,因为有一些有用的提示。

于 2012-07-05T08:25:13.060 回答
3

不知道我应该使用什么参数?

由于参数的模糊性,包括许多开发人员在内的许多开发人员在开始编写 AsyncTask 时都遇到了困难。很大的原因是我们试图记住 AsyncTask 中使用的参数。关键是不要背。如果您可以可视化您的任务真正需要做什么,那么使用正确的签名编写 AsyncTask 将是小菜一碟。

什么是异步任务?

AsyncTask 是在后台线程中运行的后台任务。它接受一个输入,执行进度并给出输出。

IE AsyncTask<Input,Progress,Output>

只要弄清楚你的输入、进度和输出是什么,你就可以开始了。

例如

在此处输入图像描述

参数如何doInbackground()变化AsyncTask

在此处输入图像描述

doInBackground()onPostExecute(),onProgressUpdate()有什么关系 ?

在此处输入图像描述

你怎么能在代码中写这个?

 DownloadTask extends AsyncTask<String,Integer,String>{

    @Override
    public void onPreExecute(){
    }

    @Override
    public String doInbackGround(String... params)
    {
         // Download code
         int downloadPerc = // calculate that
         publish(downloadPerc);

         return "Download Success";
    }

    @Override
    public void onPostExecute(String result)
    {
         super.onPostExecute(result);
    }

    @Override
    public void onProgressUpdate(Integer... params)
    {
         // show in spinner, access UI elements
    }

}

您将如何在您的活动中运行此任务?

new DownLoadTask().execute("Paradise.mp3");
于 2019-01-25T08:52:44.837 回答
0

自从提出这个问题以来已经有几年了(并且自从有人发布了回复)。根据Android 的官方文档,从那时起,ProgressDialog 在 API 级别 O 中被弃用。因此,您可以考虑使用内联进度条而不是文档作者建议的 ProgressDialog。

于 2017-04-25T18:19:20.743 回答
-2

This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.

于 2017-04-28T19:16:46.930 回答