Android几种异步的实现

文章目录

      • 用Java方法来实现异步
          • 1、继承Thread类
          • 2、实现Runnable接口
      • 使用Android 特有的方法实现异步
          • 1、AsyncTask
          • 2、Handler
          • 3、RxJava

用Java方法来实现异步

主要有两种方法来实现异步,继承Thread类和实现Runnable接口

1、继承Thread类
public class MyThread extends Thread{
	private String str;
	public MyThread(String str){
		this.str= str;
	}
	@Override
	public void run(){
		System.out.println(str);
		runOnUIThread(new Runnable() {
    		//此处更新UI
		});
	}
}
public class MainText{
	public static void main(String[] args){
		MyThread thread1= new MyThread("myThread1");
		MyThread thread2= new MyThread("myThread2");
		MyThread thread3= new MyThread("myThread3");
		thread1.start();
		thread2.start();
		thread3.start();
	}
}
2、实现Runnable接口
public class MyThreadRunnable implements Runnable{
	private String str;
	public MyThreadRunnable(String str){
		this.str = str;
	}
	@Override
	public void run(){
		System.out.print(str);
		runOnUIThread(new Runnable(){
			//此处更新UI
		}
	}
}

public class MainTest{
	public static void main(String[] args){
		MyThreadRunnable thread1 = new MyThreadRunnable("runnable1");
		MyThreadRunnable thread2 = new MyThreadRunnable("runnable2");
		Thread t1 = new Thread(thread1);
		Thread t2 = new Thread(thread2);
		t1.start();
		t2.start();
	}
}

//或者直接  使用内部类:
new Thread(new Runnable(){
	@Override
	public void run(){
		System.out.print("执行耗时或者异步操作");
		runOnUIThread(new Runnable(){
			//此处更新UI
		});
	}
});

使用Android 特有的方法实现异步

1、AsyncTask

实现一个内部类并继承AsyncTask类,并重写方法

public class MainActivity extends Activity{
	private ProgressBar mProgressBar;
	private ImageView mImageView;
	@Override
	public void onCreate(................){
		MyAsyncTask myAsyncTask = new MyAsyncTask();
		myAsyncTask.execute("www.baidu.com/xxx.jpg");
	}
}

class MyAsyncTask extends AsyncTask{
	@Override
	protected void onPreExecture(){
		//这里是开始线程之前执行的,是在UI线程
		mProgressBar.setMax(100);
		super.onPreExecute();
	}
	@Override
	protected Bitmap doInBackground(String... params){
		//这是在后台子线程中执行的
		Bitmap bitmap = null;
		try{
			URL url = new URL(params[0]);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			InputStream stream = connection.getInputStream();
			bitmap = BitmapFactory.decodeStream(inputStrem);
			publishProgress(70); //这里是更新进度
			inputStream.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return bitmap;
	}
	@Override
	protected void onCancelled(){
		//当任务被取消时回调
		super.onCancelled();
	}
	@Override
	protected void onProgressUpdate(Integer... values){
		super.onP......(values);
		//更新进度
		mProgressBar.setProgress(values[0]);
	}
	@Override
	protected void onPostExecute(Bitmap bitmap){
		super............(bitmap);
		//当任务执行完成时调用,在UI线程
		mImageView.setImageBitmap(bitmap);
	}
}

使用AsyncTask来实现异步简单便携,各个过程都有明确的回调,过程可控,但是缺点就是要是执行多个异步,就会变得很复杂

2、Handler

Handler 用来解决线程间通信,可以在子线程中提醒UI线程更新组件

public class HandlerTextActivity extends Activity{
	Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message mas){
			switch(mas.what){
				case 0:
					//此处进行UI的更新
					break;
			}
		}
	}
	@Override
	public void onCreate(......................){
		new Thread(new Runnable(){
			//在子线程中执行耗时任务,执行完毕后需要通过 Handler 通知UI线程更新UI
			mHandler.sendEmptyMessage(0);
		}).start();
	}
}

主线程也可以发消息给子线程:

public class LooperThreadActivity extends Activity {

    private Handler mHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new MyThread().start();
        //发消息到目标子线程
        mHandler.obtainMessage(0).sendToTarget();

    }

    class MyThread extends Thread{

        @Override
        public void run() {
            super.run();
            //1.建立消息循环,初始化Looper
            Looper.prepare();
            mHandler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    int what = msg.what;
                    if(what == 0){
                        //
                    }
                }
            };
            //启动消息循环
            Looper.loop();
        }
    }
}

3、RxJava
public class RxJavaTestActivity extends Activity {

    private ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Observable.just("")
                .map(new Func1() {
                    @Override
                    public Bitmap call(String s) {
                        //可以在这里执行耗时操作,比如下载网络图片,然后转化为Bitmap
                        return null;
                    }
                }).subscribeOn(Schedulers.io())//把工作线程指定为了IO线程
                .observeOn(AndroidSchedulers.mainThread())//把回调线程指定为了UI线程
                .subscribe(new Action1() {
                    @Override
                    public void call(Bitmap bitmap) {
                        //这里是在UI线程,这里显示了图片
                        mImageView.setImageBitmap(bitmap);
                    }
                });
    }
}

你可能感兴趣的:(android)