一个简单的AsyncTast小例子

    这个例子的效果是打开APP后主界面有一个按钮,点击按钮后,线程休眠5S,然后打开一张图片

MainActivity

package com.weixi.asynctask;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends ActionBarActivity {
private Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn= (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i =new Intent(MainActivity.this,ImageActivity.class);
                startActivity(i);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
ImageActivity

package com.weixi.asynctask;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by 风华国乐 on 2016/7/20.
 */
public class ImageActivity extends Activity {
    public ImageView img;
    public ProgressBar pro;
    public static String URL = "https://img-my.csdn.net/uploads/201504/12/1428806103_9476.png";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image);
        img = (ImageView) findViewById(R.id.img);
        pro = (ProgressBar) findViewById(R.id.pro);
        new MyAsyncTask().execute(URL);
    }



    class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
        //异步执行后台线程所要完成的任务

        @Override
        protected Bitmap doInBackground(String... params) {
            String url = params[0];
            Bitmap bitmap = null;
            URLConnection connection;
            InputStream is;

            try {
                connection = new URL(url).openConnection();//获取网络对象
                is = connection.getInputStream();//获取输入流
                BufferedInputStream bis = new BufferedInputStream(is);
                Thread.sleep(5000);
                bitmap = BitmapFactory.decodeStream(bis);//将输入流解析成bitmap
                is.close();
                bis.close();

            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return bitmap;
        }


        //执行后台耗时操作前被调用,一般被用于初始化操作
        @Override

        protected void onPreExecute() {
            pro.setVisibility(View.VISIBLE);

            super.onPreExecute();
        }
        //在后台耗时操作执行完后会自动执行该方法,并将结果传给该方法

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            pro.setVisibility(View.GONE);
            img.setImageBitmap(bitmap);
            super.onPostExecute(bitmap);
        }

        //在第一个方法中调用publishProgress()方法更新任务的执行进度后,会触发该方法

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }

}
主activity的xml文件
<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="lingyige "/>

</LinearLayout>
ImageActivity的xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/img"/>
    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="gone"
        android:id="@+id/pro"/>





</RelativeLayout>



这是跟着慕课网的eclipse_xu老师写的例子,希望对大家理解AsyncTast有所帮助

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值