Android_AsyncTask异步任务(一)

AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程

好了,我们就看看效果

activity_main.xml

<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.example.multithreadind01.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/textView1"
        android:layout_marginRight="53dp"
        android:text="Button" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_marginTop="84dp" >
    </ListView>

    <!-- 进度条 -->
    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/listView1"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="28dp" />

</RelativeLayout>

效果图:

 

  

 

 

item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <TextView 
        android:id="@+id/username"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:textSize="45dp"
     android:text="1" /> <TextView android:id="@+id/sex" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="60dp" android:textSize="45dp"
android:text="2" /> </LinearLayout>

 效果图:

 

java代码: User实体类

package com.example.multithreadind01;

public class User {
    private String username;
    private String sex;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

}

 

MainActivity.java

package com.example.asynctask;

import java.util.ArrayList;
import java.util.List;


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;


public class MainActivity extends Activity {
    private TextView tv1;//item.xml里的TextView:Textviewname
    private TextView tv2;//item.xml里的TextView:Textviewage
    private Button bt;//activity_main.xml里的Button
    private ListView lv;//activity_main.xml里的ListView
    private BaseAdapter adapter;//要实现的类
    private List<User> userList = new ArrayList<User>();//实体类
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        bt = (Button) findViewById(R.id.Button);
        lv = (ListView) findViewById(R.id.listView1);
      
        //模拟数据库
        for (int i = 0; i < 5; i++) {
            User ue = new User();//给实体类赋值
            ue.setName("小米"+i);
            ue.setAge("18");
            userList.add(ue);
        }
      
        bt.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
            MyTask mt = new MyTask(MainActivity.this);
                mt.execute(userList,adapter);//里面的参数是传给doInBackground
                
                
            }
        });
        
        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return userList.size();//数目
            }
            
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                LayoutInflater inflater = MainActivity.this.getLayoutInflater();
                View view;
                 
                if (convertView==null) {
                    //因为getView()返回的对象,adapter会自动赋给ListView
                    view = inflater.inflate(R.layout.item, null);
                }else{
                    view=convertView;
                    Log.i("info","有缓存,不需要重新生成"+position);
                }
                tv1 = (TextView) view.findViewById(R.id.Textviewname);//找到Textviewname
                tv1.setText(userList.get(position).getName());//设置参数
                
                tv2 = (TextView) view.findViewById(R.id.Textviewage);//找到Textviewage
                tv2.setText(userList.get(position).getAge());//设置参数
                return view;
            }
            @Override
            public long getItemId(int position) {//取在列表中与指定索引对应的行id
                return 0;    
            }
            @Override
            public Object getItem(int position) {//获取数据集中与指定索引对应的数据项
                return null;
            }        
        };
        lv.setAdapter(adapter);
        
    }


}

 

 

 

MyTask.java //也是继承AsyncTask这个重点的类

package com.example.asynctask;

import java.util.List;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MyTask extends AsyncTask{
    private MainActivity activity;
    private BaseAdapter adapter;
    private List<User> userList;
    public MyTask(MainActivity activity){
        this.activity = activity;
    }
    @Override
    protected Object doInBackground(Object... params) {
        userList = (List<User>) params[0];
        adapter = (BaseAdapter) params[1];        
        for (int i = 0; i < userList.size(); i++) {
            //模拟网络
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                
            userList.get(i).setName("小红"+i);//模拟网络悄悄的更改name
            userList.get(i).setAge("2"+i);
            publishProgress(i);
        }
        return "你好";
    }
    //准备
    @Override
    protected void onPreExecute() {
        Toast.makeText(activity, "开始中", Toast.LENGTH_SHORT).show();
    }
    //做完后执行
    @Override
    protected void onPostExecute(Object result) {
            String r = result.toString();//得到返回值
            TextView tv = (TextView)activity.findViewById(R.id.textView1);
            tv.setText(r+"访问完成!");
            
        }
    //分步完成
    @Override
    protected void onProgressUpdate(Object... values) {
        
        int bar = Integer.parseInt(values[0].toString());
       
        bar = (bar+1)*20;
        ProgressBar progressBar = (ProgressBar)activity.findViewById(R.id.ProgressBar);//进度条
        progressBar.setProgress(bar);
        adapter.notifyDataSetChanged();
    }

}

 

打开效果图:

 

点击按钮效果图:

 

接着进度条开始加载;并且ListView的只也在一一更换 图下:

 

 

 最后结果:

 

posted @ 2016-12-05 20:01  小鱼干的梦  阅读(193)  评论(0编辑  收藏  举报