android 开启主线程,Android4.0不能在主线程中进行HTTP请求解决办法 1

1.在主线程开启子线程下载数据。

2.下载完毕后,向主线程发送消息。

3.在主线程的handler中处理消息。

4.加上连接网络的权限。

package com.example.hellodemo2;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLConnection;

import android.app.Activity;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.os.Handler;

import android.util.Log;

import android.widget.ImageView;

public class MainActivity extends Activity {

ImageView imageview;

Bitmap bm;

private final Handler handler = new Handler() {

@Override

public void handleMessage(android.os.Message msg) {

imageview.setImageBitmap(bm);

};

};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

imageview = (ImageView) findViewById(R.id.imageView1);

// 开启子线程连接网络

new Thread(new Runnable() {

@Override

public void run() {

// TODO Auto-generated method stub

// TODO Auto-generated method stub

long startTime = System.currentTimeMillis();

String urlstr = "http://www.molyapp.com/theme/images/start.png";

URL url;

try {

url = new URL(urlstr);

URLConnection con = url.openConnection();

HttpURLConnection imageConnection = (HttpURLConnection) con;

// 获取输入流

InputStream inputStream = imageConnection.getInputStream();

// 获取图片的长度

long length = imageConnection.getContentLength();

bm = BitmapFactory.decodeStream(inputStream);

// 获取输出流

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

byte[] buffer = new byte[4096];

int sum = 0;

int read = 0;

int bytecount = (int) Math.min(buffer.length, length - sum);

while ((read = inputStream.read(buffer, 0, bytecount)) != -1) {

// 刚开始每次读获取buffer的长度。最后读取剩下的。

byteArrayOutputStream.write(buffer, 0, read);

sum += read;

}

Log.v("haha", sum + "");

System.out.println("readBytes=" + sum);

long fetchImageTime = System.currentTimeMillis()

- startTime;

handler.sendEmptyMessage(0);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}).start();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值