From Honeycomb SDK (3), Google will no longer allow network requests (HTTP, Socket) and other related operations directly in the Main Thread class, in fact, should not do direct network operation in the UI thread, blocking UI, user experience is bad! Even if Google is not prohibited, under normal circumstances, we will not do it ~!
So, that is, in the Honeycomb SDK (3) version, you can also continue to do so in Main Thread, more than 3, it will not work.
1.use Handler
The more time-consuming operations associated with network are placed into a child thread and then communicated with the main thread using the Handler
messaging mechanism
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.use 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.use StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}