android中的痛苦线程

android中的痛苦线程,第1张

概述我的预期结果是在第一次启动时会显示一个进度对话框,等待后台线程加载内容.在工作线程完成工作后,对话框解除.我做了搜索并得到了这个解决方案HowtodisplayprogressdialogbeforestartinganactivityinAndroid?这是我的完整代码:privateManagerApplicationapp;

我的预期结果是在第一次启动时会显示一个进度对话框,等待后台线程加载内容.在工作线程完成工作后,对话框解除.我做了搜索并得到了这个解决方案How to display progress dialog before starting an activity in Android?

这是我的完整代码:

    private ManagerApplication app;    private ImageAdapter adapter;    private GrIDVIEw grIDvIEw;    @OverrIDe    public voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.main);        setupVIEw();          }    private voID setupVIEw() {        grIDvIEw = (GrIDVIEw) findVIEwByID(R.ID.grIDvIEw);        app = (ManagerApplication) getApplication();        ProgressDialog progress = new ProgressDialog(this);        progress.setMessage("Loading...");        new LoadImageTask(progress, this).execute();           }    private class LoadImageTask extends AsyncTask<VoID, VoID, VoID> {        private ProgressDialog progress;        private Context context;        public LoadImageTask(ProgressDialog progress, Context context) {            this.progress = progress;            this.context = context;        }        @OverrIDe        protected voID onPreExecute() {            super.onPreExecute();            progress.show();        }        @OverrIDe        protected VoID doInBackground(VoID... params) {            adapter = new ImageAdapter(app.getShoes(), context);            grIDvIEw.setAdapter(adapter);             return null;        }        @OverrIDe        protected voID onPostExecute(VoID result) {            super.onPostExecute(result);            progress.dismiss();        }    }

但是,我的应用程序崩溃的原因是“只有创建视图层次结构的原始线程才能触及其视图”.我认为有一些东西阻止了主UI线程,但它仍然非常不清楚.所以有人能指出我的问题吗?谢谢

解决方法:

doinBackground is non UI Thread ,So never update any UI(VIEw) in this
method…

并使用OnPostExecute或OnProgressUpdate进行更新UI

 @OverrIDe        protected VoID doInBackground(VoID... params) {           //here just background task ,     //its non UI Thread so dont set ant vIEw here set it in OnPostExecute,...            return null;        }

从setupvIEw调用asynctask

private voID setupVIEw() {        grIDvIEw = (GrIDVIEw) findVIEwByID(R.ID.grIDvIEw);        app = (ManagerApplication) getApplication();        new LoadImageTask(progress, this).execute();         }

并在OnPreExecute方法中创建ProgressDilog

ProgressDialog progress;@OverrIDe    protected voID onPreExecute() {        super.onPreExecute();     progress = new ProgressDialog(this);     progress.setMessage("Loading...");     progress.show();    }

并在onPostExecute中解雇它

总结

以上是内存溢出为你收集整理的android中的痛苦线程全部内容,希望文章能够帮你解决android中的痛苦线程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1112945.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存