用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

AsyncTask

2016-12-19 作者: 张贤伟举报

[java]代码库

package com.example.day_07asynctask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutionException;

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

public class MainActivity extends Activity {

    private ImageView imageview;
	private ProgressBar progressBar;
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageview = (ImageView) findViewById(R.id.imageview);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
    }
    public void button(View v){
    	AsyncTask<URL, Integer, Bitmap> asyncTask=new AsyncTask<URL, Integer, Bitmap>() {
			private Bitmap bitmap;
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				progressBar.setVisibility(View.VISIBLE);
			}
			@Override
			protected Bitmap doInBackground(URL... params) {
				try {
					String path="http://zxpic.gtimg.com/infonew/0/wechat_pics_-8590809.jpg/640";
					URL url=new URL(path);
					HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
					openConnection.setConnectTimeout(5000);
					openConnection.setRequestMethod("GET");
					openConnection.setReadTimeout(5000);
					openConnection.connect();
					if(200==openConnection.getResponseCode()){
						InputStream inputStream = openConnection.getInputStream();
						bitmap = BitmapFactory.decodeStream(inputStream);
						//返回
						return bitmap;
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}
			@Override
			protected void onPostExecute(Bitmap result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				imageview.setImageBitmap(bitmap);
				progressBar.setVisibility(View.GONE);
			}
		};
		asyncTask.execute();
    	
    }
    


   
}


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...