The first line of code reading notes

Broadcast mechanism

  • Standard radio
    • A broadcast performed completely asynchronously
    • After the broadcast, all broadcast receivers receive the broadcast message at approximately the same time, in no order
    • High efficiency, can not be truncated
  • Orderly broadcast
    • Synchronous broadcast execution
    • Only one broadcast receiver can receive a message at any one time and the logic in that broadcast receiver does not continue until it’s done, in order
    • The broadcast receiver with the highest priority receives the broadcast message first
    • The broadcast receiver in front can intercept the broadcast being transmitted

Receiving system broadcast

  • Broadcast receiver
  • Registration of radio
    • Dynamic registration: Registration in code
    • Static registration: Register in androidmanifest.xml
  • Create a broadcast receiver:

    Inherited fromBroadcast-receiverRewrite the parent classonReceive()

Dynamic registrations listen for network changes

public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private NetworkChangeReceiver networkChangeRecevier; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentFilter = new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); networkChangeRecevier = new NetworkChangeReceiver(); registerReceiver(networkChangeRecevier, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(networkChangeRecevier); } class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "network changes", Toast.LENGTH_SHORT).show(); }}}Copy the code
  • When the network status changes, the system sends a message with the valueandroid.net.conn.CONNECTIVITY_CHANGEThe radio
  • addAction(): What broadcasts are monitored
  • RegisterReceiver () Registers a broadcast receiver
  • Be sure to cancel your registration
  • Indicates whether the user has a network or no network
    class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo(); if (networkInfo ! = null && networkInfo.isAvailable()) { Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show(); }}}Copy the code
    • ConnectivityManager: System service class for managing network connections
    • If the program needs to perform some operations that are sensitive to users, the permissions must be declared in the configuration file

      Add to androidmanifest.xml:
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      Copy the code
  • Disadvantages: broadcast can only be received after the program is started

Static registration to achieve boot

  • Com. Example. Broadcasttest package – > New – > Ohter – > Broadcast Receiver
    • Exported: Whether to allow this broadcast receiver to receive unexpected broadcasts of this program
    • Enabled: Whether to enable the broadcast receiver
    public class BootCompleteReceiver extentds BroadcastReceiver { @Override public void onReceveive(Context context, Intent intent) { Toast.makeText(context, "Boot Complete", Toast.LENGTH_LONG).show(); }}Copy the code
    • Static broadcast receivers must be registered in androidmanifest.xml to be used
    • The broadcast receiver created by the shortcut is automatically registered
      <receiver
          android:name=".BootCompleteReceiver"
          android:enabled="true"
          android:exported="true"
      /receiver>
      Copy the code
    • Add permissions
      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
      Copy the code
      • Error: Missing permissions required by…

Don’t inonReceive()Method to add too much logic or perform time-consuming operations

Broadcast receiverThreads are not allowed to open

onReceive()The program will report an error if it runs for a long time without ending

The broadcast receiver acts more as a way to open other components of the program

Sends custom broadcasts

Send standard broadcast

Button button = (Button) findViewById(R.id.button); button.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST"); sendBroadcast(intent); }}));Copy the code
  • Build an Intent object and pass in the broadcast value to send
  • Call the Context of thesendBoradcast()Method to send the broadcast
  • Since the broadcast is delivered using an Intent, you can carry some data in the Intent and pass it to the broadcast receiver

Send ordered broadcast

Button button = (Button) findViewById(R.id.button); button.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST"); sendOrderedBroadcast(intent, null); }}));Copy the code
  • sendOrderedBroadcast()Receive two parameters
    • The first parameter: Intent
    • Second argument: a permission-related string
  • Set priorities: Yes<receiver>Of the label<intent-filter>Add attributes to

    android:priority="100"
  • Whether to allow the broadcast to continue: added in onReceive() for the broadcast receiverabortBroadcast();

Using local broadcasting

  • Broadcasts issued using this mechanism can only be transmitted internally within the application, and the broadcast receiver can only receive broadcasts from the application itself
  • useLocalBroadcastManagerManage the broadcast

    Methods for sending broadcasts and registering broadcast receivers are also provided

    (in the android. Support. The v4. The content in the package)
public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private LocalReceiver localReceiver; private LocalBroadcastManager localBroadcastManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); localBroadcastManager = LoacalBroadcastManager.getInstance(this); Button button = (Button) findViewById(R.id.button); button.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST"); localBroadcastManager.sendBroadcast(intent); }})); intentFilter = new IntentFilter(); intentFilter.addAction("android.net.conn.LOCAL_BROADCAST"); localReceiver = new LocalReceiver(); localBroadcastManager.registerReceiver(localReceiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); localBroadcastManager.unregisterReceiver(localReceiver); } class LocalReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "receive local broadcast", Toast.LENGTH_SHORT).show(); }}}Copy the code
  • Local broadcasts cannot be received through static registration
  • More efficient than global broadcast
  • Broadcasts do not leave the program: confidential data cannot be leaked and other programs cannot send broadcasts in, and there are no security vulnerabilities