赞
踩
1、定义一个Caller类,里面创建一个借口类OnCallListener
package com.example.interfacecallback;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Looper;
public class Caller {
public Caller() {
// TODO 自动生成的构造函数存根
}
public interface OnCallListener {
public void onCall(Bitmap bitmap);
}
public void setOnCallListener(final OnCallListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO 自动生成的方法存根
Looper.prepare(); // 类中本身没有没有Looper对象,需要在线程中创建
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.baidu.com/img/bdlogo.gif");
Bitmap bitmap = null;
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
byte[] data = EntityUtils.toByteArray(response
.getEntity());
bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
}
} catch (ClientProtocolException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
listener.onCall(bitmap);
Looper.loop(); // 循环消息队列
}
}).start();
}
}
主程序MainActivity实现接口回调
package com.example.interfacecallback;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.interfacecallback.Caller.OnCallListener;
public class MainActivity extends Activity {
private ImageView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (ImageView) findViewById(R.id.tv);
Caller caller = new Caller();
caller.setOnCallListener(new OnCallListener() {
@Override
public void onCall(Bitmap bitmap) {
// 在没有网络的情况下bitmap为空
if (bitmap == null) {
Toast.makeText(MainActivity.this, "连接网络失败",
Toast.LENGTH_SHORT).show();
} else {
tv.setImageBitmap(bitmap);
}
}
});
}
}
注意:添加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。