AsyncTask异步任务 android

 自己写着玩的,如有错误欢迎大家指出。

布局文件

  <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <TextView
        android:id="@+id/text_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Activity代码

public class MainActivity extends AppCompatActivity implements Into{
  
    private MyAsyncTask myAsyncTask;
    private ImageView imageView;
    private TextView textTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        imageView = (ImageView) findViewById(R.id.image_view);
        textTv = (TextView) findViewById(R.id.text_tv);
        myAsyncTask = new MyAsyncTask(this);
        myAsyncTask.execute();




    }

    @Override
    public void setUpBitmap(Bitmap bitmap) {
        imageView.setImageBitmap(bitmap);
    }

    @Override
    public void setUpText(String string) {
        textTv.setText(string);
    }
}
异步任务中代码

ublic class MyAsyncTask extends AsyncTask<String,Integer,Bitmap> {


    private Bitmap bitmap;
    private Into into;

    public MyAsyncTask(Into into) {
        this.into = into;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        try {
            URL url = new URL("http://img2.7624.net/uploads/20170207/20170207085020259.png");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if (connection.getResponseCode()==200){
                InputStream inputStream = connection.getInputStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();
                for (int i = 5; i > 0; i--) {
                    Thread.sleep(1000);
                    publishProgress(i);
                }


            }

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


        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
         into.setUpBitmap(bitmap);
            into.setUpText(String.valueOf(values[0]));


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
}

Into接口中代码

public interface Into {

    void setUpBitmap(Bitmap bitmap);
    void setUpText(String string);

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值