An app will throw this exception if it requests a network operation in the main thread. The Android design is designed to prevent the Web request from being too long and causing the interface to suspend animation.
There are two solutions, one using Strictmode, and two using threads to manipulate network requests.
The first method: simple violence, forced use, code modification simple (but very not recommended) in the Mainactivity file Setcontentview (R.layout.activity_main) under the following code
| 1234 |
if(android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = newStrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);} |
The second method is that I use the method is also I want to recommend the method, the request network resources of the code to use the thread to operate. Make HTTP requests in Runnable without blocking the UI thread.
| 123456789101112131415161718192021222324252627 |
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.main_view); new Thread(runnable).start();}Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle data = msg.getData(); String val = data.getString("value"); Log.i(TAG,"请求结果:" + val); }}Runnable runnable = new Runnable(){ @Override public void run() { // TODO: http request. Message msg = new Message(); Bundle data = new Bundle(); data.putString("value","请求结果"); msg.setData(data); handler.sendMessage(msg); }} |
Above is a more general method, my Code:
| 12345678 |
// Android 4.0 之后不能在主线程中请求HTTP请求 new Thread(new Runnable(){ @Override public void run() { cachedImage = asyncImageLoader.loadDrawable(imageUrl, position); imageView.setImageDrawable(cachedImage); } }).start(); |