• android笔记--AsyncTask例子


    代码:

    package com.test.handler;
     
    import com.test.demo.R;
     
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.TextView;
     
    public class AsyncTaskTestActivity extends Activity {
     
        private TextView textView;
        private ProgressDialog dialog;
        
        //Counter 用于保存中间结果
        private class Counter {
            public int progress;
            public int sum;
     
            public Counter(int progress, int sum) {
                this.progress = progress;
                this.sum = sum;
            }
     
        }
        
    //定义AsyncTask子类,传给任务的参数Void,处理中间结果类型为Counter类型,处理最终结果为Integer类型
        private class MyTask extends AsyncTask<Void, Counter, Integer> {
            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                textView.setText("result:0");
                dialog.show();
            }
     
            @Override
            protected Integer doInBackground(Void... params) {
                int sum = 0;
                try {
                    for (int i = 0; i < 100; i++) {
                        sum += i * 2;
                        //发布中间结果,onProgressUpdate函数对中间结果进行处理,可以在UI组件上显示进度
                        publishProgress(new Counter(i, sum));
                        Thread.sleep(40);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
                //返回最终处理结果
                return Integer.valueOf(sum);
            }
     
            @Override
            protected void onProgressUpdate(Counter... values) {
                // 中间结果处理:设置进度条,textView上显示目前累加的结果
                dialog.setProgress(values[0].progress);
                textView.setText("result:" + values[0].sum);
     
            }
            
            // doInBackground处理完成后执行
            @Override
            protected void onPostExecute(Integer result) {
                super.onPostExecute(result);
                dialog.dismiss();
                textView.setText("result:" + result);
            }
        }
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_handler_test2);
            dialog = new ProgressDialog(this);
            dialog.setTitle("start");
            dialog.setIcon(R.drawable.ic_dialog_load);
            dialog.setMessage("please wait");
            dialog.setMax(100);
            dialog.setProgress(0);
            dialog.setIndeterminate(false);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setCancelable(false);
     
            textView = (TextView) findViewById(R.id.result2);
     
        }
     
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.handler_test2, menu);
            return true;
        }
     
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            } else if (id == R.id.action_reflash2) {
            	//启动任务,每次都是创建新的任务对象
                new MyTask().execute();
                return true;
            }
     
            return super.onOptionsItemSelected(item);
        }
     
    }
    

     layout文件:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.test.handler.AsyncTaskTestActivity" >
    
        <TextView
            android:id="@+id/result2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
    
    </RelativeLayout>
    

    Android doc上给出的规定:

    Threading rules


    There are a few threading rules that must be followed for this class to work properly:

  • 相关阅读:
    爬虫的简单运用
    预测体育竞技比赛结果(新人练手)
    自己的第一个网页
    科学计算和可视化(numpy及matplotlib学习笔记)
    面向对象总结
    PIL库的总结及运用
    jirba库的使用和好玩的词云
    第一次结队作业
    四则运算版本升级
    自动生成小学四则运算项目练习(已更新)
  • 原文地址:https://www.cnblogs.com/xiaozu/p/4502157.html
Copyright © 2020-2023  润新知