作者:女孩明天_会更好 | 来源:互联网 | 2023-09-01 09:56
主要是异步任务类的一个小例子。AsyncTask类用于异步执行任务。使用它必须继承AsyncTask,而且指定3个泛型值:Params:传给执行任务的参数值类型Progr
主要是异步任务类的一个小例子。
AsyncTask 类用于异步执行任务。使用它必须继承AsyncTask,而且指定3个泛型值:
Params:传给执行任务的参数值类型
Progress: 任务在后台执行的进度条类型,通常为Integer。
Result: 执行完任务的返回值类型
AsyncTask的子类必须要实现doInBackground的方法,通常在改方法执行后台任务,除此之外还有
onPoseExecute方法 :任务执行完后被调用
onProgressUpdata 方法 : 任务处理的过程中调用, 也传递当前进度值, 主要是调用AsyncTask.publishProcess方法后会调用
onCanceled:(当任务取消时被调用)
其中onPostExecute,onProgressUpdate和onCancel方法中都可以访问UI线程的控件,doInBackground只能访问非Ui线程控件的代码
因为涉及到网络 记得要添加网络权限
public class MainActivity extends Activity implements OnClickListener { private Button startBtn; private Button stopBtn; private MyAsyncTask myAsyncTask; private String imgPath = "http://c.hiphotos.baidu.com/image/pic/item/37d12f2eb9389b50bdca45c68735e5dde7116e69.jpg"; private Bitmap bm; private ProgressDialog mProgressDialog; private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { mImageView = (ImageView) findViewById(R.id.imageView1); startBtn = (Button) findViewById(R.id.button1); stopBtn = (Button) findViewById(R.id.button2); startBtn.setOnClickListener(this); stopBtn.setOnClickListener(this); mProgressDialog = new ProgressDialog(this); mProgressDialog.setTitle("提示信息"); mProgressDialog.setMessage("正在下载中..."); mProgressDialog.setCanceledOnTouchOutside(false); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); } class MyAsyncTask extends AsyncTask { @Override protected Void doInBackground(String... params) { // TODO Auto-generated method stub ByteArrayOutputStream bos= new ByteArrayOutputStream(); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(params[0]); InputStream is = null; try { HttpResponse httpRespOnse= httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { is = httpResponse.getEntity().getContent(); long sum = httpResponse.getEntity().getContentLength(); byte[] buffer = new byte[1024]; int count = 0; int process = 0; while ((count = is.read(buffer)) != -1) { bos.write(buffer, 0, count); process = process + count; publishProgress((int) (process / (float) sum * 100)); } byte[] data = bos.toByteArray(); bm = BitmapFactory.decodeByteArray(data, 0, data.length); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(bos != null){ try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); mImageView.setImageBitmap(bm); mProgressDialog.cancel(); Toast.makeText(MainActivity.this, "download successfully", Toast.LENGTH_SHORT).show(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); Log.i("jiayou", "values" + values[0]); mProgressDialog.setProgress(values[0]); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: onClick_start(); break; case R.id.button2: onClick_stop(); break; default: break; } } private void onClick_stop() { myAsyncTask.cancel(true); mProgressDialog.cancel(); } private void onClick_start() { myAsyncTask = new MyAsyncTask(); myAsyncTask.execute(imgPath); mProgressDialog.show(); } }
布局文件
xmlns:tools="http://schemas.android.com/tools" android:layout_ android:layout_ android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:cOntext=".MainActivity" > android:id="@+id/button1" android:layout_ android:layout_ android:layout_alignParentTop="true" android:layout_centerHorizOntal="true" android:layout_marginTop="57dp" android:text="start" /> android:id="@+id/button2" android:layout_ android:layout_ android:layout_alignLeft="@+id/button1" android:layout_below="@+id/button1" android:text="stop" /> android:id="@+id/imageView1" android:layout_ android:layout_ android:layout_centerHorizOntal="true" android:layout_below="@+id/button2" android:scaleType="fitCenter" android:layout_marginTop="66dp" />