編輯:關於 Android 程式設計
通信,顧名思義,就是資訊的傳遞與交換。在 Android 這套龐大的體系裡,通信貫穿始終,是每一名開發者都必須跨過的門檻。
依照目錄索引,你可以系統性地掌握以下內容:
1. 組件間通信:Activity、Fragment、Service、Provider、Receiver;
2. 進程間通信:AIDL;
3. 線程間通信:Handler、AsyncTask、IntentService;
4. 多個 App 之間的通信;
5. 借助大型開源框架完成組件通信:EventBus、Otto;
6. 網絡通信基礎篇:Google 課程——AsyncTask + HttpClient;
7. 網絡通信提高篇:開源框架 Async-HttpClient、OkHttp、Retrofit。
1. 研究對象:Activity、Fragment 等組件;
2. 資訊的存在形式:Intent、Bundle、靜態變數、全局變數,或是點擊、觸摸事件的回調監聽,又或者以檔案形式(SharedPreferences、SQLite、File、NetStream)存在,本質上都是資訊源;
3. 資訊的傳遞形式:網絡、回調監聽、線程、Intent、全局 Application;
4. 相同形式的思路:一通百通,請讀者舉一反三;
5. 研究對象始終單一,一次只聚焦一個目標。
Activity 與 Activity
1. 常規方式:Intent + Bundle
透過 Intent 啟動另一個 Activity 時,有兩種重載方式:
startActivity(new Intent(), new Bundle());
startActivityForResult(new Intent(), FLAG, new Bundle());
從參數列表不難看出,核心就是 Intent 與 Bundle,能傳遞 8 種基本資料型別以及可序列化的資料型別(比如字串、位元組陣列)。說到可序列化,就不得不提 Intent 與 Bundle 的局限:
其一,它們無法傳遞「不可序列化」的資料,比如 Bitmap、InputStream。解法有很多,最簡單的就是把這類物件轉換成位元組陣列(因主題是通信,這裡不展開)。其二,Intent 與 Bundle 能傳遞的資料大小限制在 40K 以內。
補充一句:很多人不解為何總把 Intent 和 Bundle 並肩討論,原因很簡單——Intent 底層存儲資訊的原理,正是透過 Bundle!
2. 公有靜態變數
例如 public static String flag = "中國"; 在其他 Activity 中,直接 FirstActivity.flag = "china"; 就能修改它的值。
3. 基於物理形式
比如 File、SQLite、SharedPreferences 這類以檔案為載體的形式。
4. 全局變數
例如 Application。它與 Activity、Service 齊名,功能強大,最大特點是全局共用、以單例形式存在。在其他組件中,只需透過 Context.getApplication() 即可拿到它的參照。
Activity 與 Fragment、Service、BroadcastReceiver
它們都遵循一條原則:如何啟動它們,就如何傳遞資訊。
1. Activity 與 Fragment
可以透過建構函數傳遞,也可以先取得 Fragment 的實例物件:
//CustFragment 是自定義的fragment,參數列表也可以自己定義咯, getSupportFragmentManager().beginTransaction() .add(new CustFragment(自定義的的參數列表),new String("參數")) //------------------method two----------------------- getSupportFragmentManager().findFragmentById(R.id.headlines_fragment); //------------------method three---------------------- getSupportFragmentManager().findFragmentByTag("HeadLines");
聰明的讀者可能會反問:那 Fragment 又如何與 Activity 通信呢?這是個好問題。請記住我們的「單一目標原則」,本節聚焦的是 Activity,你的疑惑會在後文一一解答。
2. Activity 與 Service
Activity 啟動 Service 有兩種方式:
//CustomService 是自定義Service,完成一些後台操作 startService(new Intent(FirstActivity.this, CustomService.class)); bindService(new Intent(FirstActivity.this, CustomService.class)), new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { } @Override public void onServiceDisconnected(ComponentName name) { } },flags);
從啟動方式便能看出,它是透過 Bundle 存儲、Intent 傳輸,來完成 Activity 向 Service 傳遞資料。
3. Activity 與 BroadcastReceiver
啟動廣播同樣有兩種形式:
//method one registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { } },new IntentFilter(),"",new Handler()); //method two registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { } },new IntentFilter());
關於 method one 的第三個參數 Handler,很多人頗感困惑。查閱 registerReceiver 源碼中的說明:它定義了一個用於接收 Intent 的子線程,若不填或設為 null,則會在主線程中完成接收。可見 Activity 與 BroadcastReceiver 通信,用的依然是 Intent 傳遞、Bundle 存儲。
4. 通信中的同步問題
以上大多是靜態的資料傳遞。但有一種更進階的需求:當用戶在 Activity 上按下、滑動、觸摸,發出某些指令時,如何完成資訊傳遞?這就要求「同步」了。同步傳遞其實很簡單,就是呼叫系統寫好的回調介面。
首先要認識到,用戶的點擊、觸摸行為同樣屬於通信範疇——它們是資訊源。比如用戶點擊時:
new Button(mCotext).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new ImageView(mCotext).invalidate(); } });
這一招等於在提醒指定的 ImageView:「老兄,該刷新了!」又比如用戶觸摸時,我們想實現指定區域的縮放與平移:
new RelativeLayout(mCotext).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { v.setScaleX(1f); v.setScaleY(1f); v.setTranslationX(1f); v.setTranslationY(1f); v.setRotation(2f); v.setRotationX(2f); v.setRotationY(2f); v.invalidate(); return true; } });
你看,透過回調 onTouchListener,就能從容應對「觸摸」這類操作。(關於 View 的重繪機制與刷新優化,不在本文討論範圍之內。)
1. Fragment 與 Activity 通信
同樣透過實例物件傳遞。在 Fragment 中呼叫 getActivity() 即可拿到關聯的 Activity 實例,進而輕鬆讀寫它的資料。
2. Fragment 與多個 Fragment 通信
兩個 Fragment 之間無法直接通信(非正規手段除外),Google 官方給出的方案是「透過關聯的 Activity 來中轉」。只需記牢三步:
第一步:定義一個介面。在 Fragment 中定義介面,讓宿主 Activity 來實作它,並在 onAttach() 中捕獲 Activity 實例。
public class HeadlinesFragment extends ListFragment { OnHeadlineSelectedListener mCallback; public interface OnHeadlineSelectedListener { public void onArticleSelected(int position); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallback = (OnHeadlineSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } }
一旦 Activity 透過 mCallback 回調 onArticleSelected(),Fragment 便能向 Activity 傳遞資訊了。比如下面這個 ListFragment 的回調:當用戶點擊列表項時,它就透過介面向宿主 Activity 傳遞事件。
@Override public void onListItemClick(ListView l, View v, int position, long id) { mCallback.onArticleSelected(position); }
第二步:在宿主 Activity 中實作這個介面。
public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { //響應用戶的操作,做一些業務邏輯 } }
第三步:向其他 Fragment 傳遞資訊,完成通信。宿主 Activity 可以透過 findFragmentById() 拿到指定 Fragment,直接回調它的公有方法。例如:
public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { ArticleFragment articleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.article_fragment); if (articleFrag != null) { articleFrag.updateArticleView(position); } else { ArticleFragment newFragment = new ArticleFragment(); Bundle args = new Bundle(); args.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(args); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, newFragment); transaction.setTransition(TRANSIT_FRAGMENT_OPEN); transaction.addToBackStack(null); transaction.commit(); } } }
各個類的聯繫圖與運行效果如下:


Service 與 Activity 通信
核心是如何拿到 Service 實例,總結起來兩步:其一,在 Service 中定義一個繼承 Binder 的內部類,封裝 Service 作為屬性,並在 onBind 中返回它;其二,在 Activity 中實作 ServiceConnection,取得 Binder 物件後再取出 Service。
public class LocalService extends Service { private final IBinder mBinder = new LocalBinder(); private final Random mGenerator = new Random(); public class LocalBinder extends Binder { LocalService getService() { return LocalService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } public int getRandomNumber() { return mGenerator.nextInt(100); } }
public class BindingActivity extends Activity { LocalService mService; boolean mBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, LocalService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); if (mBound) { unbindService(mConnection); mBound = false; } } public void onButtonClick(View v) { if (mBound) { int num = mService.getRandomNumber(); Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show(); } } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; }
除了這種回調方式,還有一招:在 Service 中發送廣播。比如在 Service 開啟一個子線程執行任務,就在 run() 方法裡呼叫 sendBroadcast(intent),資料用 Intent 封裝,傳遞形式則用廣播。
先建立兩個基本概念。關於進程與線程:當某個應用組件啟動、而該應用又沒有其他組件在運行時,Android 會用單個執行線程為它啟動一個新的 Linux 進程;預設情況下,同一應用的所有組件都在相同進程與線程(即「主」線程)中運行。清單文件中 activity、service、receiver、provider 均支援 android:process 屬性,可用來指定組件運行在哪個進程。
關於進程間通信:Android 借助遠程過程調用(RPC)提供了一種進程間通信(IPC)機制,由 Activity 或其他組件呼叫的方法會在其他進程中遠程執行,結果再回傳給呼叫方。要執行 IPC,必須使用 bindService() 將應用綁定到服務上。具體實現可參考文末的官方文檔。
Handler 與 AsyncTask 都是用來完成子線程與主線程(UI 線程)通信的利器,都能化解「主線程處理耗時操作導致界面卡頓甚至 ANR」這一頑疾。
Handler 是一套機制(Handler + Message + Looper):資料由 Message 攜帶,執行順序按隊列排布,Looper 負責輪詢消息隊列,Handler 負責接收與發送 Message。AsyncTask 則是一個獨立的類,設計初衷是異步完成耗時操作並順帶通知主線程刷新 UI,內部維護了一個線程池以提升性能。
這裡再介紹一種優雅的線程間通信做法——擴展 IntentService 類。由於大多數啟動服務並不需要同時處理多個請求(多線程反而可能引入危險),使用 IntentService 值得一試。它會:創建默認工作線程,在主線程之外執行傳遞給 onStartCommand() 的所有 Intent;創建工作隊列,將 Intent 逐一交給 onHandleIntent(),讓你永遠不必操心多線程問題;處理完所有請求後自動停止服務,無需呼叫 stopSelf();並提供 onBind()(返回 null)與 onStartCommand() 的默認實現。因此你只需實作 onHandleIntent() 即可。
public class HelloIntentService extends IntentService { public HelloIntentService() { super("HelloIntentService"); } @Override protected void onHandleIntent(Intent intent) { long endTime = System.currentTimeMillis() + 5*1000; while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (Exception e) { } } } } }
對於 Service,當然也有更基礎的多線程做法,只是程式碼量更大:
public class HelloService extends Service { private Looper mServiceLooper; private ServiceHandler mServiceHandler; private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { long endTime = System.currentTimeMillis() + 5*1000; while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (Exception e) { } } } stopSelf(msg.arg1); } } @Override public void onCreate() { HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; mServiceHandler.sendMessage(msg); return START_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } }
首先要理解:Android 應用通常由若干 Activity 組成,每個 Activity 展示一個界面。要把用戶從一個 Activity 引導到另一個,需要使用 Intent 定義「意向」。當我們用 startActivity() 把 Intent 交給系統,系統便會依 Intent 識別並啟動相應組件,甚至可以啟動另一個應用中的 Activity。Intent 可以是顯式的(啟動特定組件),也可以是隱式的(啟動能處理該操作的任意組件)。
1. 向另一個應用發送用戶
Android 的一大魅力,是能操作其他應用。比如想在自家應用裡用地圖展示公司地址,我們無需自己造一個地圖 Activity,只要發出一個「查看地址」的 Intent,系統便會啟動合適的地圖應用。
1)構建隱式 Intent——不指明組件類名,只聲明操作(查看、編輯、發送等)。
Uri number = Uri.parse("tel:5551234"); Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
查看地圖與網頁:
Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California"); Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
Uri webpage = Uri.parse("https://www.android.com"); Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
至於 Intent 能傳遞哪些 Uri 或資料型別,查閱 Google 的 Intent API 便是。
2)確認是否存在可接收 Intent 的應用。注意:若設備上沒有能處理該 Intent 的應用,程式將崩潰。可用 queryIntentActivities() 事先確認:
PackageManager packageManager = getPackageManager(); List activities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); boolean isIntentSafe = activities.size() > 0;
3)啟動指定 Activity:確認安全後,startActivity(intent) 即可。
4)顯示應用選擇器:像「分享」這種用戶可用多個 App 完成的場景,就該明確彈出選擇器。使用 Intent.createChooser() 創建並傳給 startActivity():
Intent intent = new Intent(Intent.ACTION_SEND); ... String title = getResources().getString(R.string.chooser_title); Intent chooser = Intent.createChooser(intent, title); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(chooser); }
2. 接收其他 Activity 返回的結果
透過 startActivityForResult() 完成,啟動時需指定 request code 以便回來時正確處理。
static final int PICK_CONTACT_REQUEST = 1; private void pickContact() { Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts")); pickContactIntent.setType(Phone.CONTENT_TYPE); startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); }
用戶完成操作返回後,系統會回呼 onActivityResult():
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_CONTACT_REQUEST) { if (resultCode == RESULT_OK) { //完成我們的業務邏輯 } } }
要正確處理結果,就得了解 Intent 的格式——比如聯繫人回傳的是帶內容的 URI,相機回傳的是 Bitmap。讀取 URI 資料需要具備 ContentResolver 與 ContentProvider 的知識。下面是一個三者結合的獲取聯繫人實例:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_CONTACT_REQUEST) { if (resultCode == RESULT_OK) { Uri contactUri = data.getData(); String[] projection = {Phone.NUMBER}; Cursor cursor = getContentResolver() .query(contactUri, projection, null, null, null); cursor.moveToFirst(); int column = cursor.getColumnIndex(Phone.NUMBER); String number = cursor.getString(column); } } }
3. 讓其他應用啟動你的 Activity
需要在清單文件的相應元素中加上 intent-filter:
其中要定義操作(通常是系統定義值,如 ACTION_SEND 或 ACTION_VIEW)、透過 android:mimeType 指定接收的資料型別,且所有隱式 Intent 都以 CATEGORY_DEFAULT 定義。
4. 處理 Activity 中的 Intent
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = getIntent(); Uri data = intent.getData(); if (intent.getType().indexOf("image/") != -1) { } else if (intent.getType().equals("text/plain")) { } }
5. 向指定 Activity 返回資料——呼叫 setResult 指定結果碼與 Intent:
Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri"); setResult(Activity.RESULT_OK, result); finish();
切記必須指定結果碼,通常為 RESULT_OK 或 RESULT_CANCELED。若原始 Activity 呼叫的是 startActivityForResult(),系統會把 setResult() 的結果回傳給它;否則結果會被忽略。
GitHub 上廣受追捧的兩大通信框架是 EventBus 與 Otto,這裡重點說說 EventBus。
EventBus 是一個事件發布/訂閱框架,透過解耦發布者與訂閱者來簡化事件傳遞。相比 Handler、BroadcastReceiver、介面回調這些傳統方式,它最大的優點是程式碼簡潔、使用簡單,並把發布與訂閱充分解耦。
幾個核心概念:事件(Event)就是一個物件,可以是網絡請求回傳的字串,也可以是某個開關狀態;事件分為一般事件與 Sticky 事件,後者的特點是即便訂閱者較晚才訂閱,仍能收到最近一個 Sticky 事件。訂閱者(Subscriber)透過 register 訂閱、unregister 退訂,並支援優先級,高優先級者可攔截事件不再向下分發。發布者(Publisher)則透過 post 發布事件。
總體設計與流程圖:

使用方式:在 build.gradle 中加入依賴:
compile 'org.greenrobot:eventbus:3.0.0'
程式碼只需三步。定義事件(一個普通 Java 類即可)、完成訂閱者、在 Activity 或 Fragment 中綁定:
@Subscribe public void onMessageEvent(MessageEvent event){ Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show(); }
@Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); }
最後發布事件:
EventBus.getDefault().post(new MessageEvent("Hello everyone!"));
至於網絡通信的進階內容(Async-HttpClient、OkHttp、Retrofit 等),本文暫未展開,有興趣的讀者可另行深入研究。
Vitamio 本地視頻播放器實作
實作目標本文以 Android Studio 整合 Vitamio,實作一個可播放本機視頻文件的播放器。除了基本的播放控制,還包含亮度調整、音量調整、多點手勢縮放,以及自
《Android 源碼設計模式解析與實戰》讀書筆記(二十二):享元模式 Flyweight
第二十二章 享元模式(Flyweight) 享元模式是結構型設計模式之一,本質上是對象池的一種實現。顧名思義,它強調共享對象、避免重複創建。我們常用的 String 就採
Android Fragment 使用詳解
Fragment 自 Android 3.0 開始引入,中文常翻譯為「碎片」。它的主要目的,是讓開發者能更靈活地組合 UI,特別是在平板與手機等不同尺寸畫面上,動態調整版
Android GPS 定位實戰:從 NMEA 到衛星信噪比圖表
這個 GPS 測試程式最早寫於 2011 年,那時剛接觸 Android 開發,純粹是练手的實驗作品。最近因為工作需求又把它翻出來重寫,順手把定位服務相關的知識重新梳理了