一、测试一
下面通过代码演示一个典型的异步处理的实例--加载网络图片.网络操作作为一个不稳定的耗时操作,从4.0开始就被严禁放入主线程中.所以在显示一张网络图片时,我们需要在异步处理中下载图片,并在UI线程中设置图片
1、 新建项目Async2
- 主窗口增加一个按钮
- 增加新的Activity,名称为ImageActivity,添加imageView和progressBar
MainActivity.java
package com.example.administrator.async2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button btn_image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_image = (Button) findViewById(R.id.btn_image);
btn_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,ImageActivity.class));
}
});
}
}
ImageActivity.java
package com.example.administrator.async2;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
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.*;
public class ImageActivity extends AppCompatActivity {
private ImageView imageView ;
private ProgressBar progressBar ;
private static String URLs = "http://p5.qhimg.com/t0193f0ca27a17798d4.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
imageView = (ImageView) findViewById(R.id.image);
progressBar = (ProgressBar) findViewById(R.id.progress);
//通过调用execute方法开始处理异步任务.相当于线程中的start方法.
new MyAsyncTask().execute(URLs);
}
class MyAsyncTask extends AsyncTask<String,Void,Bitmap> {
//onPreExecute用于异步处理前的操作
@Override
protected void onPreExecute() {
super.onPreExecute();
//此处将progressBar设置为可见.
progressBar.setVisibility(View.VISIBLE);
}
//在doInBackground方法中进行异步任务的处理.
&