Android廣播--官方文檔(你確定完全懂了Broadcasts)

Broadcasts

Android apps can send or receive broadcast messages from the Android system and other Android apps, similar to the publish-subscribe design pattern. These broadcasts are sent when an event of interest occurs. For example, the Android system sends broadcasts when various system events occur, such as when the system boots up or the device starts charging. Apps can also send custom broadcasts, for example, to notify other apps of something that they might be interested in (for example, some new data has been downloaded).
Android應用可以從Android系統和其他Android應用發送或接收廣播消息,類似于發布 - 訂閱設計模式。當感興趣的事件發生時,這些廣播被發送。例如,當各種系統事件發生時,例如系統啟動或設備開始充電時,Android系統發送廣播。應用程序還可以發送自定義廣播,例如,通知其他應用程序可能感興趣的內容(例如,一些新數據已被下載)。

Apps can register to receive specific broadcasts. When a broadcast is sent, the system automatically routes broadcasts to apps that have subscribed to receive that particular type of broadcast.
應用程序可以注冊以接收特定的廣播。當發送廣播時,系統自動將廣播 路由到已訂閱該類型的廣播的應用。

Generally speaking, broadcasts can be used as a messaging system across apps and outside of the normal user flow. However, you must be careful not to abuse the opportunity to respond to broadcasts and run jobs in the background that can contribute to a slow system performance, as described in the following video.

System broadcasts

The system automatically sends broadcasts when various system events occur, such as when the system switches in and out of airplane mode. System broadcasts are sent to all apps that are subscribed to receive the event.
當系統發生各種系統事件時,系統會自動發送廣播,例如系統切換到飛行模式時。系統廣播將發送到已訂閱該事件的所有應用程序。
The broadcast message itself is wrapped in an Intent object whose action string identifies the event that occurred (for example android.intent.action.AIRPLANE_MODE). The intent may also include additional information bundled into its extra field. For example, the airplane mode intent includes a boolean extra that indicates whether or not Airplane Mode is on.
廣播消息本身被包裝在Intent對象中,其action字符串標識發生的事件(例如android.intent.action.AIRPLANE_MODE)。Intent還可能包含捆綁到其額外字段中的附加信息。例如,飛行模式Intent包括一個布爾值,用來表示飛行模式是否打開。

For more information about how to read intents and get the action string from an intent, see Intents and Intent Filters.
有關如何讀取intents并從intents獲取操作字符串的更多信息,請參閱intents和intent filters。

For a complete list of system broadcast actions, see the BROADCAST_ACTIONS.TXT file in the Android SDK. Each broadcast action has a constant field associated with it. For example, the value of the constant ACTION_AIRPLANE_MODE_CHANGED is android.intent.action.AIRPLANE_MODE. Documentation for each broadcast action is available in its associated constant field.
有關系統廣播操作的完整列表,請參閱Android SDK中的BROADCAST_ACTIONS.TXT文件。每個廣播動作都有一個與之相關聯的常量字段。例如,常量ACTION_AIRPLANE_MODE_CHANGED的值是android.intent.action.AIRPLANE_MODE。

Changes to system broadcasts

Android 7.0 and higher no longer sends the following system broadcasts. This optimization affects all apps, not only those targeting Android 7.0.
Android 7.0及更高版本不再發送以下系統廣播。此優化會影響所有應用,而不僅僅是針對Android 7.0的應用。

注意8.0又支持了下面的兩個廣播了,不過必須使用動態注冊。

ACTION_NEW_PICTURE
ACTION_NEW_VIDEO

Apps targeting Android 7.0 (API level 24) and higher must register the following broadcasts with [registerReceiver(BroadcastReceiver, IntentFilter)](https://developer.android.com/reference/android/content/Context.html#registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)). Declaring a receiver in the manifest does not work.
針對Android 7.0(API級別24)或更高版本的應用程序必須使用registerReceiver(BroadcastReceiver,IntentFilter)注冊以下廣播。在清單中聲明的receiver 將不起作用。
CONNECTIVITY_ACTION

Beginning with Android 8.0 (API level 26), the system imposes additional restrictions on manifest-declared receivers. If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that do not target your app specifically).
從Android 8.0(API 26級)開始,系統對在清單文件中聲明的接收器有了額外的限制。如果您的應用程序的目標API為26級或更高版本,則無法在清單文件中為絕大多數隱式廣播(不針對你應用的本地廣播)聲明接收者。

Receiving broadcasts

Apps can receive broadcasts in two ways: through manifest-declared receivers and context-registered receivers.
應用有兩種方式接收廣播:靜態注冊和動態注冊。

Manifest-declared receivers

If you declare a broadcast receiver in your manifest, the system launches your app (if the app is not already running) when the broadcast is sent.
如果你是靜態注冊,當接收到廣播的時候,系統會喚醒你的應用。

Note: If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for implicit broadcasts (broadcasts that do not target your app specifically), except for a few implicit broadcasts that are exempted from that restriction. In most cases, you can use scheduled jobs instead.
如果您的應用程序針對26級或更高級別的API,則無法使用清單聲明隱式廣播的接收者(不針對本地廣播),除了幾個免除該限制的隱式廣播。在大多數情況下,您可以使用scheduled jobs。

To declare a broadcast receiver in the manifest, perform the following steps:

  1. Specify the <receiver> element in your app's manifest.
<receiver android:name=".MyBroadcastReceiver"  android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
    </intent-filter>
</receiver>

The intent filters specify the broadcast actions your receiver subscribes to.

  1. Subclass BroadcastReceiver and implement [onReceive(Context, Intent)](https://developer.android.com/reference/android/content/BroadcastReceiver.html#onReceive(android.content.Context, android.content.Intent)). The broadcast receiver in the following example logs and displays the contents of the broadcast:
    一個繼承BroadcastReceiver并且重寫onReceive(Context, Intent).方法的子類。
public class MyBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "MyBroadcastReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        StringBuilder sb = new StringBuilder();
        sb.append("Action: " + intent.getAction() + "\n");
        sb.append("URI: " + intent.toUri(Intent.URI_INTENT_SCHEME).toString() + "\n");
        String log = sb.toString();
        Log.d(TAG, log);
        Toast.makeText(context, log, Toast.LENGTH_LONG).show();
    }
}

The system package manager registers the receiver when the app is installed. The receiver then becomes a separate entry point into your app which means that the system can start the app and deliver the broadcast if the app is not currently running.
當應用程序安裝成功后系統軟件包管理器就會注冊接收器。然后,接收器將成為您的應用程序的單獨入口點,這意味著即使應用程序當前沒有處于運行狀態,系統也可以啟動應用程序并傳送廣播。

The system creates a new BroadcastReceiver component object to handle each broadcast that it receives. This object is valid only for the duration of the call to [onReceive(Context, Intent)](https://developer.android.com/reference/android/content/BroadcastReceiver.html#onReceive(android.content.Context, android.content.Intent)). Once your code returns from this method, the system considers the component no longer active.
系統會創建一個新的BroadcastReceiver組件對象來處理它接收的每個廣播。此對象僅在調用onReceive(Context,Intent)的持續時間內有效。一旦您的代碼從此方法返回,系統將認為該組件對象不再有效。

Context-registered receivers

  1. To register a receiver with a context, perform the following steps:
    Create an instance of BroadcastReceiver.
    BroadcastReceiver br = new MyBroadcastReceiver();
    創建一個BroadcastReceiver實例。
  2. Create an IntentFilter and register the receiver by calling [registerReceiver(BroadcastReceiver, IntentFilter)](https://developer.android.com/reference/android/content/Context.html#registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)):
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
this.registerReceiver(br, filter);

Note: To register for local broadcasts, call [LocalBroadcastManager.registerReceiver(BroadcastReceiver, IntentFilter)](https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html#registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)) instead.
注意:請使用LocalBroadcastManager.registerReceiver(BroadcastReceiver, IntentFilter)方法注冊本地廣播。

Context-registered receivers receive broadcasts as long as their registering context is valid. For an example, if you register within an Activity context, you receive broadcasts as long as the activity is not destroyed. If you register with the Application context, you receive broadcasts as long as the app is running.

只要其注冊時的context 有效就會一直接收廣播。例如,如果您在Activity中注冊,只要Activity未被銷毀,就能接收廣播。如果您使用應用程序上下文注冊,只要應用程序正在運行,您就一直能接收到廣播。

  1. To stop receiving broadcasts, call unregisterReceiver(android.content.BroadcastReceiver). Be sure to unregister the receiver when you no longer need it or the context is no longer valid.
    調用[unregisterReceiver(android.content.BroadcastReceiver)]停止接收廣播。(https://developer.android.com/reference/android/content/Context.html#unregisterReceiver(android.content.BroadcastReceiver))。當您不再需要它或context不再有效時,請務必注銷接收器。
    Be mindful of where you register and unregister the receiver, for example, if you register a receiver in onCreate(Bundle) using the activity's context, you should unregister it in onDestroy() to prevent leaking the receiver out of the activity context. If you register a receiver in onResume(), you should unregister it in onPause() to prevent registering it multiple times (If you don't want to receive broadcasts when paused, and this can cut down on unnecessary system overhead). Do not unregister in onSaveInstanceState(Bundle), because this isn't called if the user moves back in the history stack.
    注意注冊和注銷接收者的時機,例如,如果您使用Activity作為上下文,在onCreate(Bundle)中注冊了一個接收者,那么您應該在onDestroy()中注銷它,以防止將接收者從Activity上下文中泄漏。如果您在onResume()中注冊了一個接收器,您應該在onPause()中注銷它,以防多次注冊(如果您不想在onPause時接收廣播,這樣還可以減少不必要的系統開銷)。不要在onSaveInstanceState(Bundle)中取消注冊,因為該方法不一定會被回調。

Effects on process state

The state of your BroadcastReceiver (whether it is running or not) affects the state of its containing process, which can in turn affect its likelihood of being killed by the system. For example, when a process executes a receiver (that is, currently running the code in its onReceive() method), it is considered to be a foreground process. The system keeps the process running except under cases of extreme memory pressure.
BroadcastReceiver的狀態(無論是否運行)會影響其所在進程的狀態,從而影響該進程被系統殺死的可能性。例如,某個進程執行一個receiver 操作(onReceive()方法中的代碼)時,它被認為是一個前臺進程。系統保持進程運行,除非是內存極端吃緊的情況下,不然該進程是不會被殺死的。
However, once your code returns from onReceive(), the BroadcastReceiver is no longer active. The receiver's host process becomes only as important as the other app components that are running in it. If that process hosts only a manifest-declared receiver (a common case for apps that the user has never or not recently interacted with), then upon returning from onReceive(), the system considers its process to be a low-priority process and may kill it to make resources available for other more important processes.
然而,一旦你的代碼從onReceive()返回,BroadcastReceiver就不再活躍了。其所在的進程的等級就和app中其他組件的等級一樣了。如果該進程僅托管清單文件中聲明的接收者(尤其是那些用戶有一段時間沒有使用的App),則在從onReceive()返回時,系統將該進程視為低優先級進程,并且可能殺死它以使資源可用于其他更重要的進程。

For this reason, you should not start long running background threads from a broadcast receiver. After onReceive(), the system can kill the process at any time to reclaim memory, and in doing so, it terminates the spawned thread running in the process. To avoid this, you should either call goAsync() (if you want a little more time to process the broadcast in a background thread) or schedule a JobService from the receiver using the JobScheduler, so the system knows that the process continues to perform active work. For more information, see Processes and Application Life Cycle.
因此,您不應該在廣播接收器中啟動長時間運行的后臺線程。在onReceive()之后,系統可以隨時殺死進程以回收內存,這樣做會終止在進程中生成并正在運行的線程。為避免這種情況,您應該調用goAsync()(如果您希望在后臺線程中多一些時間來處理廣播)或使用JobScheduler從接收方調度JobService,則系統會知道該進程需要繼續進行運行。有關更多信息,請參閱Processes and Application Life Cycle。

The following snippet shows a BroadcastReceiver that uses goAsync() to flag that it needs more time to finish after onReceive() is complete. This is especially useful if the work you want to complete in your onReceive() is long enough to cause the UI thread to miss a frame (>16ms), making it better suited for a background thread.
以下片段顯示了BroadcastReceiver,它使用goAsync()來標記在onReceive()完成后需要更多時間來完成工作。如果您要在onReceive()中完成的工作足夠長,導致UI線程錯過了一幀(> 16ms),這種情況更適合使用后臺線程,這一點尤其有用。

public class MyBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "MyBroadcastReceiver";

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final PendingResult pendingResult = goAsync();
        AsyncTask<String, Integer, String> asyncTask = new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... params) {
                StringBuilder sb = new StringBuilder();
                sb.append("Action: " + intent.getAction() + "\n");
                sb.append("URI: " + intent.toUri(Intent.URI_INTENT_SCHEME).toString() + "\n");
                Log.d(TAG, log);
                // Must call finish() so the BroadcastReceiver can be recycled.
                pendingResult.finish();
                return data;
            }
        };
        asyncTask.execute();
    }
}

Sending broadcasts

Android provides three ways for apps to send broadcast:
Android為應用發送廣播提供了三種方式:

  • The [sendOrderedBroadcast(Intent, String)](https://developer.android.com/reference/android/content/Context.html#sendOrderedBroadcast(android.content.Intent, java.lang.String)) method sends broadcasts to one receiver at a time. As each receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won't be passed to other receivers. The order receivers run in can be controlled with the android:priority attribute of the matching intent-filter; receivers with the same priority will be run in an arbitrary order.

sendOrderedBroadcast(Intent,String)方法 每次向一個接收方發送廣播。隨著每個接收機依次執行,它可以將結果傳播到下一個接收器,或者它可以完全中止廣播,使得它不會被傳遞到其他接收器。接收器的運行順序可以通過設置ntent-filter中的android:priority屬性進行控制;具有相同優先級的接收器將以任意順序運行。

  • The endBroadcast(Intent) method sends broadcasts to all receivers in an undefined order. This is called a Normal Broadcast. This is more efficient, but means that receivers cannot read results from other receivers, propagate data received from the broadcast, or abort the broadcast.
    sendBroadcast(Intent)方法以未定義的順序向所有接收者發送廣播。這被稱為普通廣播。這更有效率,但是意味著一個接收器不能從另一個接收器讀取結果,傳遞從廣播接收的數據,或者中止廣播
  • The LocalBroadcastManager.sendBroadcast method sends broadcasts to receivers that are in the same app as the sender. If you don't need to send broadcasts across apps, use local broadcasts. The implementation is much more efficient (no interprocess communication needed) and you don't need to worry about any security issues related to other apps being able to receive or send your broadcasts.The following code snippet demonstrates how to send a broadcast by creating an Intent and calling sendBroadcast(Intent).

LocalBroadcastManager.sendBroadcast方法將廣播發送到與發送方在同一個應用程序中的接收者。如果您不需要跨應用發送廣播,請使用本地廣播。實施效率更高(無需進行進程間通信),您無需擔心接收到其他應用程序的廣播或者發送廣播到其他應用程序之類的安全問題。

Intent intent = new Intent();
intent.setAction("com.example.broadcast.MY_NOTIFICATION");
intent.putExtra("data","Notice me senpai!");
sendBroadcast(intent);

The broadcast message is wrapped in an Intent object. The intent's action string must provide the app's Java package name syntax and uniquely identify the broadcast event. You can attach additional information to the intent with putExtra(String, Bundle). You can also limit a broadcast to a set of apps in the same organization by calling setPackage(String) on the intent.
廣播消息包裝在Intent對象中。Intent的action字段必須設置為應用程序的Java全包名稱,來標識廣播事件的唯一性。您可以使用putExtra(String,Bundle)添加附加信息到Intent。您還可以通過對Intent對象調用setPackage(String)將廣播限制在同一organization 中的一組應用程序。

Note: Although intents are used for both sending broadcasts and starting activities with startActivity(Intent), these actions are completely unrelated. Broadcast receivers can't see or capture intents used to start an activity; likewise, when you broadcast an intent, you can't find or start an activity.
注意:雖然internts即可以作為發送廣播的參數也可以作為啟動Activity的參數(使用startActivity(Intent)),但這些操作是完全不相關的。廣播接收者無法查看或捕獲用于start Activity的Intent;同樣地,當您廣播Intent時,您無法通過該intent找到或啟動一個Activity

Restricting broadcasts with permissions

Permissions allow you to restrict broadcasts to the set of apps that hold certain permissions. You can enforce restrictions on either the sender or receiver of a broadcast.
權限允許您將廣播限制在擁有某些權限的一組應用程序。您可以對廣播的發送者或接收者強制執行限制

Sending with permissions

When you call [sendBroadcast(Intent, String)](https://developer.android.com/reference/android/content/Context.html#sendBroadcast(android.content.Intent, java.lang.String)) or [sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)](https://developer.android.com/reference/android/content/Context.html#sendOrderedBroadcast(android.content.Intent, java.lang.String, android.content.BroadcastReceiver, android.os.Handler, int, java.lang.String, android.os.Bundle)), you can specify a permission parameter. Only receivers who have requested that permission with the tag in their manifest (and subsequently been granted the permission if it is dangerous) can receive the broadcast. For example, the following code sends a broadcast:
當您調用sendBroadcast(Intent,String)或sendOrderedBroadcast(Intent,String,BroadcastReceiver,Handler,int,String,Bundle)時,可以指定權限參數。只有接收者已經在其清單中請求了該權限(并且隨后被許可,如果它是危險的權限)才可以接收廣播。例如,以下代碼發送廣播:
sendBroadcast(new Intent("com.example.NOTIFY"),Manifest.permission.SEND_SMS);
To receive the broadcast, the receiving app must request the permission as shown below:
要接收廣播,接收應用程序必須如下所示請求權限:
<uses-permission android:name="android.permission.SEND_SMS"/>
You can specify either an existing system permission like SEND_SMS or define a custom permission with the <permission> element. For information on permissions and security in general, see the System Permissions.
您可以指定現有系統權限(如SEND_SMS)或使用<permission>元素定義自定義權限。有關權限和安全性的信息,請參閱系統權限。

Note: Custom permissions are registered when the app is installed. The app that defines the custom permission must be installed before the app that uses it.

Receiving with permissions

If you specify a permission parameter when registering a broadcast receiver (either with [registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)](https://developer.android.com/reference/android/content/Context.html#registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter, java.lang.String, android.os.Handler)) or in <receiver> tag in your manifest), then only broadcasters who have requested the permission with the<uses-permission>tag in their manifest (and subsequently been granted the permission if it is dangerous) can send an Intent to the receiver.
如果在注冊廣播接收者(或者通過registerReceiver(BroadcastReceiver,IntentFilter,String,Handler)或者清單中的<receiver>標簽)中指定權限參數時,則只有使用<uses-permission>標簽在其清單中請求了(并且隨后被許可,如果權限屬于危險權限)的broadcasters 才可以向接收者發送意圖。

For example, assume your receiving app has a manifest-declared receiver as shown below:

<receiver android:name=".MyBroadcastReceiver"
          android:permission="android.permission.SEND_SMS">
    <intent-filter>
        <action android:name="android.intent.action.AIRPLANE_MODE"/>
    </intent-filter>
</receiver>

Or your receiving app has a context-registered receiver as shown below:
或者你的應用使用以下方式進行了動態注冊。

IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(receiver, filter, Manifest.permission.SEND_SMS, null );

Then, to be able to send broadcasts to those receivers, the sending app must request the permission as shown below:
然后,為了能夠向這些接收者發送廣播,發送應用程序必須如下所示請求許可:
<uses-permission android:name="android.permission.SEND_SMS"/>

Security considerations and best practices

Here are some security considerations and best practices for sending and receiving broadcasts:
以下是發送和接收廣播的一些安全注意事項和最佳做法:

  • If you don't need to send broadcasts to components outside of your app, then send and receive local broadcasts with the LocalBroadcastManager which is available in the Support Library. The LocalBroadcastManager is much more efficient (no interprocess communication needed) and allows you to avoid thinking about any security issues related to other apps being able to receive or send your broadcasts. Local Broadcasts can be used as a general purpose pub/sub event bus in your app without any overheads of system wide broadcasts.
    如果您不需要將廣播發送到應用程序之外的組件,則可以通過支持庫中提供的LocalBroadcastManager發送和接收本地廣播。 LocalBroadcastManager效率更高(無需進行進程間通信),并允許您避免考慮與其他可以接收或發送廣播的應用程序相關的任何安全問題。本地廣播可以用作應用程序中的通用發布/接收事件總線,而無需系統廣播的任何開銷。
  • If many apps have registered to receive the same broadcast in their manifest, it can cause the system to launch a lot of apps, causing a substantial impact on both device performance and user experience. To avoid this, prefer using context registration over manifest declaration. Sometimes, the Android system itself enforces the use of context-registered receivers. For example, the CONNECTIVITY_ACTION broadcast is delivered only to context-registered receivers.
    如果許多應用程序已注冊在其清單中接收相同的廣播,則可能導致系統啟動大量應用程序,從而對設備性能和用戶體驗產生重大影響。為了避免這種情況,優先使用動態注冊。有時,Android系統本身強制使用動態。例如,CONNECTIVITY_ACTION廣播僅傳遞給動態注冊的接收者。
  • Do not broadcast sensitive information using an implicit intent. The information can be read by any app that registers to receive the broadcast. There are three ways to control who can receive your broadcasts:
    不要使用隱含意圖廣播敏感信息。任何注冊接收廣播的應用都可以讀取信息。有三種方法可以控制誰可以接收您的廣播:
    • You can specify a permission when sending a broadcast.
      您可以在發送廣播時指定權限。
    • In Android 4.0 and higher, you can specify a package with setPackage(String) when sending a broadcast. The system restricts the broadcast to the set of apps that match the package.
      在Android 4.0及更高版本中,您可以在發送廣播時使用setPackage(String)指定包。系統將廣播限制到與包相匹配的一組應用程序。
    • You can send local broadcasts with LocalBroadcastManager.
      使用本地廣播
  • When you register a receiver, any app can send potentially malicious broadcasts to your app's receiver. There are three ways to limit the broadcasts that your app receives:
    當您注冊接收者時,任何應用都可能會將惡意廣播發送到您的應用的接收者。有三種方法來限制您的應用收到的廣播:
    • You can specify a permission when registering a broadcast receiver.
      注冊廣播接收者時可以指定一個權限。
    • For manifest-declared receivers, you can set the android:exported attribute to "false" in the manifest. The receiver does not receive broadcasts from sources outside of the app.
      對于清單聲明的接收器,您可以在清單中將android:exports屬性設置為“false”。接收器不會從應用程序之外的來源接收廣播。
    • You can limit yourself to only local broadcasts with LocalBroadcastManager.
      可以限制自己只使用本地廣播。
  • The namespace for broadcast actions is global. Make sure that action names and other strings are written in a namespace you own, or else you may inadvertently conflict with other apps.
    廣播動作的命名空間是全局的。確保操作名稱和其他字符串寫在您擁有的命名空間中,否則您可能會無意中與其他應用程序沖突。
  • Because a receiver's onReceive(Context, Intent) method runs on the main thread, it should execute and return quickly. If you need to perform long running work, be careful about spawning threads or starting background services because the system can kill the entire process after onReceive() returns. For more information, see Effect on process state To perform long running work, we recommend:
    因為接收者的onReceive(Context,Intent)方法在主線程上運行,所以它應該快速執行并返回。如果您需要執行長時間的工作,請注意生成線程或啟動后臺服務,因為系統可以在onReceive()返回后終止整個進程。有關詳細信息,請參閱對Effect on process state來執行一個長時間任務,我們建議:
    • Calling goAsync() in your receiver's onReceive() method and passing the BroadcastReceiver.PendingResult to a background thread. This keeps the broadcast active after returning from onReceive(). However, even with this approach the system expects you to finish with the broadcast very quickly (under 10 seconds). It does allow you to move work to another thread to avoid glitching the main thread.
      在接收器的onReceive()方法中調用goAsync(),并將BroadcastReceiver.PendingResult傳遞給后臺線程。這樣可以在從onReceive()返回后保持廣播有效。然而,即使使用這種方法,系統也希望您可以快速完成播放(10秒以下)。它允許您將工作移動到另一個線程,以避免阻塞主線程。
    • Scheduling a job with the JobScheduler. For more information, see Intelligent Job Scheduling.
      使用JobScheduler來調度一個job。有關詳細信息,請參閱Intelligent Job Scheduling。
  • Do not start activities from broadcast receivers because the user experience is jarring; especially if there is more than one receiver. Instead, consider displaying a notification.
    不要從廣播接收機開始活動,特別是如果有多個接收器的情況下,用戶體驗會很震撼。相反,請考慮顯示一個通知。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1.廣播的分類 (1)按照發送的方式分類 標準廣播是一種異步的方式來進行傳播的,廣播發出去之后,所有的廣播接收者幾...
    曹豐斌閱讀 34,210評論 0 22
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,242評論 25 708
  • 本人初學Android,最近做了一個實現安卓簡單音樂播放功能的播放器,收獲不少,于是便記錄下來自己的思路與知識總結...
    落日柳風閱讀 19,221評論 2 41
  • 諸多無奈,最近在改一個項目的bug的時候,腦子老是一片空白,可能是最近腦子不夠用,總之,好多東西忘了,閱讀一些別人...
    狗子王1948閱讀 7,737評論 6 53
  • 有萬千思緒卻不足以表達,從學校的無知到社會的無奈,從那時無話不說到此時不安忐忑, 第一次戀愛是在初二時,她是那...
    A不負勇往閱讀 296評論 0 8