自己写着玩的,如有错误欢迎大家指出。
布局文件
<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);
}