【Android通訊】Android線程間通訊

Android程序中,線程分爲主線程(UI thread)和工作線程(work thread)。我們要遵循單線程模型原則:安卓UI的操作線程不安全,安卓UI的操作必須在主線程進行。

1、多線程任務開發可以通過以下幾個方式實現:Handler、AsyncTask。詳見:http://blog.csdn.net/qq_29266921/article/details/54893254

2、如果子線程的數據想通知到UI線程中,實現方法:

Activity.runOnUIThread(Runnable)

runOnUiThread(new Runnable(){//更新UI
                    @Override
                    public void run() {
                        publish_time.setText("更新失敗");
                    }
                    
                });

view.post(Runnable)或者new Handler().post()

view.post本質上是異步消息處理機制。相對於新建Handler進行處理更加便捷,參考一下源碼

public boolean post(Runnable action) {    
  final AttachInfo attachInfo = mAttachInfo;
  if (attachInfo != null) {       
  return attachInfo.mHandler.post(action);
  }    
// Assume that post will succeed later       
  ViewRootImpl.getRunQueue().post(action); 
  return true;
}
post方法相當於把這個事件添加到了UI 事件隊列尾部,保證了在layout結束以後才執行。

view.postDelayed(Runnable, long)或者new Handler().postDelayed(Runnable, long)

3.管道流(不常用),管道爲兩個線程建立一個單向的通道。生產者PipedWriter負責寫數據,消費者PipedReader負責讀取數據。感覺很繁瑣,不想用。

public class PipeExampleActivity extends Activity {

	private static final String TAG = "PipeExampleActivity";
	private EditText editText;

	PipedReader r;
	PipedWriter w;

	private Thread workerThread;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		r = new PipedReader();
		w = new PipedWriter();

		try {
			w.connect(r);
		} catch (IOException e) {
			e.printStackTrace();
		}

		setContentView(R.layout.activity_pipe);
		editText = (EditText) findViewById(R.id.edit_text);
		editText.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
			}

			@Override
			public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
				try {
					if(count > before) {
						w.write(charSequence.subSequence(before, count).toString());
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void afterTextChanged(Editable editable) {
			}
		});

		workerThread = new Thread(new TextHandlerTask(r));
		workerThread.start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		workerThread.interrupt();
		try {
			r.close();
			w.close();
		} catch (IOException e) {
		}
	}

	private static class TextHandlerTask implements Runnable {
		private final PipedReader reader;

		public TextHandlerTask(PipedReader reader){
			this.reader = reader;
		}
		@Override
		public void run() {
			while(!Thread.currentThread().isInterrupted()){
				try {
					int i;
					while((i = reader.read()) != -1){
						char c = (char) i;
						
						Log.d(TAG, "char = " + c);
					}

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

4.共享內存(不常用,除非存在高併發,例如火車票之類的APP)

synchronized(this) {
    while(isConditionFullfilled == false) {
        wait();
    }


    notify();
}
3、4請參考:http://www.tuicool.com/articles/7NZnayB


發佈了80 篇原創文章 · 獲贊 65 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章