在android中主线程(UI线程)不能执行耗时操作:时间比较长(ANR application no response ) 、网络操作(直接抛异常)
因为android的主线程是不安全线程!!!!为了提高速度!!!主线程没有进行同步操作
三种主流解决方案:
1、异步操作
2、handle
3、Loader
两种非主流解决方案:
4、view.post(new ..)
5、runOnUiThread(new Runnable(){})
-----------------------------------------------------------------------------------------
异步任务:
异步: 三个泛型和四个步骤
同步:
异步任务下载一张图片的例子:
package com.example.myapplication; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity{ private ImageView imageView; private EditText url; private HttpURLConnection conn; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.imageview); url = (EditText) findViewById(R.id.edittext); } public void go(View view){ final String urtStr = url.getText().toString(); MyTask task = new MyTask(); task.execute(urtStr); } public class MyTask extends AsyncTask<String, Integer, Bitmap>{ @Override protected void onProgressUpdate(Integer... values){ Log.e("onProgressUpdate", Thread.currentThread().getName()); super.onProgressUpdate(values); } @Override protected void onPreExecute(){ super.onPreExecute(); } @Override protected Bitmap doInBackground(String... params){ try{ String urtStr = params[0]; URL url = new URL(urtStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){ InputStream is = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(is); return bitmap; } }catch(Exception e){ e.printStackTrace(); }finally{ if(conn != null){ conn.disconnect(); } } return null; } @Override protected void onPostExecute(Bitmap s){ if(s != null){ imageView.setImageBitmap(s); } super.onPostExecute(s); } } }