zoukankan      html  css  js  c++  java
  • AsyncTask doinbackground onProgressUpdate onCancelled onPostExecute的基本使用

    对于异步操作的原理我就不讲了。在这我着重讲怎么使用异步操作的doinbackground onProgressUpdate onCancelled onPostExecute这四个方法

    doinbackground 我的理解效果相当于Thread里面的run。这样理解就easy多了,由于大家可能对Thread都非常熟悉,你能够把你想要首先处理的事物放在这里,可是有非常多人就会在这里更新ui操作。这是不能够的 ,要更新ui操作我们就要讲到onPostExecute这种方法啦

    onPostExecute我们把它先override 出来看看他的结构
    @Override

            protected void onPostExecute(List<GovernmentInstitutionBean> result) {}

    我们能够看到方法里面有一个result參数,类型是自定义的,那么这个result是从哪里传来的呢,没错了,通过doinbackground处理将结果返回给
    onPostExecute方法result接收。在这种方法里面更新ui操作。List这个类型也不是凭空而来。而是在doinbackground方法里面也要设置
    首先你得把方法的返回类型改一下

        protected List<GovernmentInstitutionBean> doInBackground(Void... arg0) {

    然后你得把类的參数改一下

    class Task1 extends AsyncTask<Void, Void, List<GovernmentInstitutionBean>>

    在doinbackground方法里面有个return 把你想要返回的数据return

    override onPostExecute方法自然就能接收到了

    说到这里你应该会简单的使用异步操作了,假设你还想要对它更细化的控制。异常的处理那么 onProgressUpdate onCancelled 这两个方法就呼吁而出了

    onProgressUpdate 就是在你正在进行异步操作的时候提示用户你正在操作,让你的应用体验更加好,那么这种方法的使用也非常easy

    首先你得覆盖它

        @Override
            protected void onProgressUpdate(Void... values) {
                // TODO Auto-generated method stub
            }

    然后你得触发它

    publishProgress();

    在你想要触发正在处理的地方添上即可,至于你在onProgressUpdate里面作什么,一般都是弹窗,我这里是用progressdialog提示正在载入,那么就是这种

        @Override
            protected void onProgressUpdate(Void... values) {
                // TODO Auto-generated method stub
                pd = ProgressDialog.show(IndustrialPark_Activity.this, "提示信息",
                        "正在载入…");
            }

    在doinbackground方法一開始就弹出正在载入

        protected List<GovernmentInstitutionBean> doInBackground(Void... arg0) {
                // TODO Auto-generated method stub
    
                try {
                    publishProgress();
                    .....
                    .....
                    ......

    那么这里要注意的是,假设载入成功的话就会跳到onpostexcute方法里面,假设载入失败的话呢。那么我们要让它跳到oncancelled方法里面,我们try catch一下doinbackground方法里面的处理,在catch里面加上

    cancel(true);

    这句代码,不管跳到哪都要记得你的pd还没消失呢。所以在两个方法里面都要写上让它消失的代码handler。sendmeesage…();

    那么整个流程就讲的差点儿相同了。喜欢的请点赞,评论。不喜勿喷。

  • 相关阅读:
    【基础算法】- 全排列
    【基础算法】- 2分查找
    区块链培训
    Static Binding (Early Binding) vs Dynamic Binding (Late Binding)
    test
    No data is deployed on the contract address!
    "throw" is deprecated in favour of "revert()", "require()" and "assert()".
    Variable is declared as a storage pointer. Use an explicit "storage" keyword to silence this warning.
    京都行
    Failed to write genesis block: database already contains an incompatible
  • 原文地址:https://www.cnblogs.com/yfceshi/p/7294396.html
Copyright © 2011-2022 走看看