Honeycomb SDK (3) から、Google はネットワーク リクエスト (HTTP、ソケット) およびその他の関連操作をメイン スレッド クラスで直接許可しなくなります。実際、UI スレッドで直接ネットワーク操作を行うべきではなく、UI をブロックし、ユーザー エクスペリエンスが悪い!Googleが禁止されていなくても、通常の状況では、私たちはそれをしません~! つまり、Honeycomb SDK (3) のバージョンでは、メイン スレッドでも引き続き実行できますが、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);
}