从Honeycomb SDK(3)开始,Google将不再允许在Main Thread类中直接进行网络请求(HTTP、Socket)等相关操作,实际上不应该在UI线程中直接进行网络操作,阻塞UI,用户体验很差!就算不禁止谷歌,一般情况下,我们也不会这样做~!
所以,也就是在Honeycomb SDK(3)版本中,你也可以在Main Thread中继续这样做,超过3就不行了。
1.使用Handler
与网络相关的比较耗时的操作放在子线程中,然后使用Handler消息机制与主线程通信
public static final String TAG = "NetWorkException";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_net_work_exception);
// Opens a child thread, performs network operations, waits for a return result, and uses handler to notify UI
new Thread(networkTask).start();
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// get data from msg and notify UI
Bundle data = msg.getData();
String val = data.getString("data");
Log.i(TAG, "the result-->" + val);
}
};
/**
* net work task
*/
Runnable networkTask = new Runnable() {
@Override
public void run() {
// do here, the HTTP request. network requests related operations
Message msg = new Message();
Bundle data = new Bundle();
data.putString("data", "request");
msg.setData(data);
handler.sendMessage(msg);
}
};
2.使用AsyncTask
public static final String TAG = "NetWorkException";
private ImageView mImageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_net_work_exception);
mImageView = findViewById(R.id.image_view);
new DownImage(mImageView).execute();
}
class DownImage extends AsyncTask<String, Integer, Bitmap> {
private ImageView imageView;
public DownImage(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
Bitmap bitmap = null;
try {
//load image from internet , http request here
InputStream is = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
// nodify UI here
imageView.setImageBitmap(result);
}
}
3.使用StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}