Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android App 後台服務如何向上游報告工作狀態

編輯:Android 開發實例

後台服務把活幹完了,總得讓發起方知道結果。本節介紹一種既安全又輕量的做法:借助 LocalBroadcastManager 收發狀態廣播。相比全局廣播,它的廣播範圍被限制在本應用進程內,既避免了信息外洩,也省下了跨進程的開銷。

從 IntentService 發出狀態

思路分兩步。第一步,構造一個攜帶狀態與數據的 Intent,按需還可以附加 action 與 URI;第二步,調用 LocalBroadcastManager.sendBroadcast() 把它發出去,應用內所有注册了該廣播的接收器都會收到。實例通過 LocalBroadcastManager.getInstance() 獲取。

public final class Constants {
    ...
    // Defines a custom Intent action
    public static final String BROADCAST_ACTION =
            "com.example.android.threadsample.BROADCAST";
    ...
    // Defines the key for the status "extra" in an Intent
    public static final String EXTENDED_DATA_STATUS =
            "com.example.android.threadsample.STATUS";
    ...
}
public class RSSPullService extends IntentService {
...
    /*
     * Creates a new Intent containing a Uri object
     * BROADCAST_ACTION is a custom Intent action
     */
    Intent localIntent =
            new Intent(Constants.BROADCAST_ACTION)
            // Puts the status into the Intent
            .putExtra(Constants.EXTENDED_DATA_STATUS, status);
    // Broadcasts the Intent to receivers in this app.
    LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
...
}

接收並處理廣播

接收方式與普通廣播一致:寫一個 BroadcastReceiver 子類並實現 onReceive()。

// Broadcast receiver for receiving status updates from the IntentService
private class ResponseReceiver extends BroadcastReceiver
{
    // Prevents instantiation
    private DownloadStateReceiver() {
    }
    // Called when the BroadcastReceiver gets an Intent it's registered to receive
    public void onReceive(Context context, Intent intent) {
...
        /*
         * Handle Intents here.
         */
...
    }
}

接著定義意圖過濾器,用來匹配指定的 action、category 與 data。

// Class that displays photos
public class DisplayActivity extends FragmentActivity {
    ...
    public void onCreate(Bundle stateBundle) {
        ...
        super.onCreate(stateBundle);
        ...
        // The filter's action is BROADCAST_ACTION
        IntentFilter mStatusIntentFilter = new IntentFilter(
                Constants.BROADCAST_ACTION);

        // Adds a data filter for the HTTP scheme
        mStatusIntentFilter.addDataScheme("http");
        ...

注册環節略有差異,需要改用 LocalBroadcastManager.registerReceiver():

 // Instantiates a new DownloadStateReceiver
        DownloadStateReceiver mDownloadStateReceiver =
                            new DownloadStateReceiver();
        // Registers the DownloadStateReceiver and its intent filters
        LocalBroadcastManager.getInstance(this).registerReceiver(
                            mDownloadStateReceiver,
                            mStatusIntentFilter);
        ...

一個 BroadcastReceiver 可以同時處理多種類型的廣播,這意味著你能依據不同 action 分派不同邏輯,而不必為每種事件各寫一個接收器:

 /*
     * Instantiates a new action filter.
     * No data filter is needed.
     */
        statusIntentFilter = new IntentFilter(Constants.ACTION_ZOOM_IMAGE);
        ...
        // Registers the receiver with the new filter
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
                            mDownloadStateReceiver,
                            mIntentFilter);

一條重要的設計原則

發送廣播既不會啟動也不會恢復 Activity。BroadcastReceiver 的作用是讓 Activity 有機會接收並處理數據——哪怕應用此時正在後台——但它絕不會把 App 硬拽回前台。如果你的目標是在用戶看不到應用時通知他發生了某事,正確工具是 Notification。反過來說,為了響應一條廣播而去啟動 Activity,是應當避免的反模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved