O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

BroadcastReceivers in Android

866 visualizações

Publicada em

In this tutorial we will review one of the basic app components
in Android - the BroadcastReceiver. The BroadcastReceiver
for subscribing your Android app for events in clean and
simple publisher-subscriber pattern.

Publicada em: Celular
  • Entre para ver os comentários

  • Seja a primeira pessoa a gostar disto

BroadcastReceivers in Android

  1. 1. Broadcast Receivers in Android Perfect APK
  2. 2. Background BroadcastReceiver is one of the basic app components in Android. It provides a clean and simple publisher subscriber pattern for Android apps. Subscribing for events can be done statically using the manifest file, or dynamically calling registerReceiver(). Publishing events is done by calling sendBroadcast(). The types of events that the BroadcastReceiver is subscribed to are called actions which are strings that are passed to system using an IntentFilter. In order to receive broadcasts from outside the app a BroadcatsReceiver must be exported. A broadcastReceiver can also require a permission for sending broadcasts to it.
  3. 3. In this tutorial In this tutorial we will go over the following examples of using Broadcast Receivers in Android: ● BroadcastReceiver in the manifest file - In this example we will see how a BroadcastReceiver is declared in the manifest file. ● Enabling and disabling a BroadcastReceiver - In this example we will learn how to programmatically enable and disable a BroadcastReceiver that is declared in the manifest file. ● BroadcastReceiver in an activity - In this example we will see how a BroadcastReceiver to use a BroadcastReceiver in order to register for events in an activity. ● Sending a broadcast - In this example we will see how to send a
  4. 4. BroadcastReceiver in the manifest file In this simple example we declare a BroadcastReceiver in the manifest file. The receiver is registered for receiving broadcasts indicating the a device boot has been completed. This broadcast is sent by the Android system using ACTION_BOOT_COMPLETED. The receiver is declared using the receiverelement. the name element is the name of the class of the receiver. The receiver is enabled and it is also exported so it can receive the broadcast from the external system component. Sending broadcast to this receiver requires RECEIVE_BOOT_COMPLETED permission which is only granted to the Android system. Finally, the receiver has an intent-filter element with ACTION_BOOT_COMPLETED. 1. <receiver 2. android:name=".BootReceiver" 3. android:enabled="true" 4. android:exported="true" 5. android:permission="android.permission.RECEIVE_BOOT_COMPLETED"> 6. 7. <intent-filter> 8. <action android:name="android.intent.action.BOOT_COMPLETED" />
  5. 5. BroadcastReceiver in the manifest file Below is the BootReceiver class. It has an empty constructor which is required for instantiation. Handling the broadcast is done in the onReceive() method. 1. public class BootReceiver extends BroadcastReceiver { 2. public BootReceiver() { 3. } 4. 5. @Override 6. public void onReceive(Context context, Intent intent) { 7. // do something 8. } 9. }
  6. 6. Enabling and disabling a BroadcastReceiver Now that we have a BroadcastReceiver, we can enable and disable it programmatically by calling setComponentEnabledSetting(). First we need a ComponentName for the receiver: 1. final ComponentName componentName = 2. new ComponentName(getApplicationContext(), BootReceiver.class); Disabling the receiver: 1. getPackageManager().setComponentEnabledSetting(componentName, 2. PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); Enabling the receiver: 1. getPackageManager().setComponentEnabledSetting(componentName, 2. PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
  7. 7. BroadcastReceiver in Activity In this example we will see an Activity that contains a Switch for enabling and disabling the Wi-Fi, and a BroadcastReceiver for monitoring the state of the Wi-Fi. First, we need to add the following permissions to the manifest file: 1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 2. <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> Next, we need to prepare the layout file for the activity. The layout includes the Wi-Fi Switch and a TextView for displaying the Wi- Fi state: 1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2. xmlns:tools="http://schemas.android.com/tools" 3. android:layout_width="match_parent" 4. android:layout_height="match_parent" 5. tools:context=".WifiToggleActivity"> 6.
  8. 8. BroadcastReceiver in Activity 1. <Switch android:id="@+id/wifiSwitch" 2. android:layout_width="wrap_content" 3. android:layout_height="wrap_content" 4. android:layout_centerInParent="true" 5. android:layout_marginTop="30dp"/> 6. 7. <TextView android:id="@+id/tvWifiState" 8. android:layout_above="@id/wifiSwitch" 9. android:layout_width="wrap_content" 10. android:layout_height="wrap_content" 11. android:layout_centerHorizontal="true" 12. android:textAppearance="?android:attr/textAppearanceMedium"/> 13.
  9. 9. BroadcastReceiver in Activity Finally, the activity class handles switch events and uses a BroadcastReceiver to monitor changes in the Wi-Fi state. Since the receiver is only used for updating the UI it is registered in the onResume() method and unregistered in the onPause() method. 1. public class WifiToggleActivity extends Activity implements CompoundButton.OnCheckedChangeListener { 2. private WifiManager mWifiManager; 3. private TextView mTvWifiState; 4. private Switch mWifiSwitch; 5. 6. private final BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() { 7. @Override 8. public void onReceive(Context context, Intent intent) { 9. onWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 10. WifiManager.WIFI_STATE_UNKNOWN));
  10. 10. BroadcastReceiver in Activity 1. 2. private final IntentFilter mWifiStateChangedIntentFilter = 3. new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION); 4. 5. @Override 6. protected void onCreate(Bundle savedInstanceState) { 7. super.onCreate(savedInstanceState); 8. setContentView(R.layout.activity_wifi_toggle); 9. mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 10. mTvWifiState = (TextView) findViewById(R.id.tvWifiState); 11. mWifiSwitch = (Switch) findViewById(R.id.wifiSwitch); 12. mWifiSwitch.setOnCheckedChangeListener(this); 13. onWifiState(mWifiManager.getWifiState());
  11. 11. BroadcastReceiver in Activity 1. @Override 2. protected void onResume() { 3. super.onResume(); 4. registerReceiver(mWifiStateReceiver, mWifiStateChangedIntentFilter); 5. } 6. 7. @Override 8. protected void onPause() { 9. unregisterReceiver(mWifiStateReceiver); 10. super.onPause(); 11. } 12. 13. @Override
  12. 12. BroadcastReceiver in Activity 1. private void onWifiState(int wifiState) { 2. switch (wifiState) { 3. case WifiManager.WIFI_STATE_DISABLED: 4. mTvWifiState.setText(R.string.wifi_state_disabled); 5. mWifiSwitch.setEnabled(true); 6. break; 7. 8. case WifiManager.WIFI_STATE_DISABLING: 9. mTvWifiState.setText(R.string.wifi_state_disabling); 10. mWifiSwitch.setEnabled(false); 11. break; 12. 13. case WifiManager.WIFI_STATE_ENABLED: 14. mTvWifiState.setText(R.string.wifi_state_enabled); 15. mWifiSwitch.setEnabled(true); 16. break; 17. 18. case WifiManager.WIFI_STATE_ENABLING: 19. mTvWifiState.setText(R.string.wifi_state_enabling); 20. mWifiSwitch.setEnabled(false); 21. break; 22. 23. default: 24. break; 25. } 26. } 27. }
  13. 13. Sending a broadcast Sending a Broadcast is done by calling sendBroadcast(). The call can specify a permission the receiver must hold in order to receive the broadcast.