zoukankan      html  css  js  c++  java
  • 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:

  • 相关阅读:
    React 实践记录 02 Flux introduction
    React 实践记录 01 组件开发入门
    IntelliJ IDEA 2018.2.2及以下版本破解方法
    Icon.png pngcrush caught libpng error:Read
    MySQL导入.sql文件及常用命令
    MySql Host is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts' 解决方法
    mysql 导出数据库命令
    MySQL 连接本地数据库、远程数据库命令
    在EC2上创建root用户,并使用root用户登录
    svn 批量添加命令
  • 原文地址:https://www.cnblogs.com/xiaozu/p/4502157.html
Copyright © 2011-2022 走看看