SlideShare une entreprise Scribd logo
1  sur  13
Broadcast 
Receivers in 
Android 
Perfect APK
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.
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
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" />
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. }
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);
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.
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.
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));
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());
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
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. }
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.

Contenu connexe

Tendances

Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI WidgetsAhsanul Karim
 
Broadcast Receivers in Android
Broadcast Receivers in AndroidBroadcast Receivers in Android
Broadcast Receivers in Androidma-polimi
 
Pandora FMS: Exchange ActivSync Plugin
Pandora FMS: Exchange ActivSync PluginPandora FMS: Exchange ActivSync Plugin
Pandora FMS: Exchange ActivSync PluginPandora FMS
 
GigaSpaces Cloud Computing Framework 4 XAP - Quick Tour - v2
GigaSpaces Cloud Computing Framework 4 XAP - Quick Tour - v2GigaSpaces Cloud Computing Framework 4 XAP - Quick Tour - v2
GigaSpaces Cloud Computing Framework 4 XAP - Quick Tour - v2Shay Hassidim
 

Tendances (6)

Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
 
Broadcast Receivers in Android
Broadcast Receivers in AndroidBroadcast Receivers in Android
Broadcast Receivers in Android
 
Pandora FMS: Exchange ActivSync Plugin
Pandora FMS: Exchange ActivSync PluginPandora FMS: Exchange ActivSync Plugin
Pandora FMS: Exchange ActivSync Plugin
 
GigaSpaces Cloud Computing Framework 4 XAP - Quick Tour - v2
GigaSpaces Cloud Computing Framework 4 XAP - Quick Tour - v2GigaSpaces Cloud Computing Framework 4 XAP - Quick Tour - v2
GigaSpaces Cloud Computing Framework 4 XAP - Quick Tour - v2
 
Learn Drupal 8 Render Pipeline
Learn Drupal 8 Render PipelineLearn Drupal 8 Render Pipeline
Learn Drupal 8 Render Pipeline
 
Recycler mvp
Recycler   mvp Recycler   mvp
Recycler mvp
 

En vedette

Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database TutorialPerfect APK
 
Getting Started With ANDROID
Getting Started With ANDROIDGetting Started With ANDROID
Getting Started With ANDROIDAmit Yadav
 
FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)Nehemiah Tan
 
Android Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs TutorialPerfect APK
 
android app development training report
android app development training reportandroid app development training report
android app development training reportRishita Jaggi
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for AndroidJakir Hossain
 
(続) Effective SQLite for Android
(続) Effective SQLite for Android(続) Effective SQLite for Android
(続) Effective SQLite for AndroidShinobu Okano
 
Android Components & Manifest
Android Components & ManifestAndroid Components & Manifest
Android Components & Manifestma-polimi
 
Introduction to Android, Architecture & Components
Introduction to  Android, Architecture & ComponentsIntroduction to  Android, Architecture & Components
Introduction to Android, Architecture & ComponentsVijay Rastogi
 
Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009Viswanath J
 
Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )Eakapong Kattiya
 

En vedette (17)

Sqlite Multiple Table
Sqlite Multiple TableSqlite Multiple Table
Sqlite Multiple Table
 
School updated
School updatedSchool updated
School updated
 
Asynctasks
AsynctasksAsynctasks
Asynctasks
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
 
Getting Started With ANDROID
Getting Started With ANDROIDGetting Started With ANDROID
Getting Started With ANDROID
 
FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)
 
Android Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs Tutorial
 
android app development training report
android app development training reportandroid app development training report
android app development training report
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for Android
 
(続) Effective SQLite for Android
(続) Effective SQLite for Android(続) Effective SQLite for Android
(続) Effective SQLite for Android
 
Android Components & Manifest
Android Components & ManifestAndroid Components & Manifest
Android Components & Manifest
 
Introduction to Android, Architecture & Components
Introduction to  Android, Architecture & ComponentsIntroduction to  Android, Architecture & Components
Introduction to Android, Architecture & Components
 
Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 
Android ppt
Android ppt Android ppt
Android ppt
 

Similaire à BroadcastReceivers in Android

Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsAndroid App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsDiego Grancini
 
Android App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsAndroid App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsDiego Grancini
 
Android broadcast receiver tutorial
Android broadcast receiver   tutorialAndroid broadcast receiver   tutorial
Android broadcast receiver tutorialmaamir farooq
 
Android Application Components-BroadcastReceiver_Content Provider.pptx
Android Application Components-BroadcastReceiver_Content Provider.pptxAndroid Application Components-BroadcastReceiver_Content Provider.pptx
Android Application Components-BroadcastReceiver_Content Provider.pptxKNANTHINIMCA
 
Android Training (Broadcast Receiver)
Android Training (Broadcast Receiver)Android Training (Broadcast Receiver)
Android Training (Broadcast Receiver)Khaled Anaqwa
 
Exercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone callExercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone callmaamir farooq
 
Android appwidget
Android appwidgetAndroid appwidget
Android appwidgetKrazy Koder
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02rhemsolutions
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx34ShreyaChauhan
 
Skinning Android for Embedded Applications
Skinning Android for Embedded ApplicationsSkinning Android for Embedded Applications
Skinning Android for Embedded ApplicationsVIA Embedded
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recieversUtkarsh Mankad
 
Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...naseeb20
 
Londroid Android Home Screen Widgets
Londroid Android Home Screen WidgetsLondroid Android Home Screen Widgets
Londroid Android Home Screen WidgetsRichard Hyndman
 
Android应用开发简介
Android应用开发简介Android应用开发简介
Android应用开发简介easychen
 
Understanding and Extending Prometheus AlertManager
Understanding and Extending Prometheus AlertManagerUnderstanding and Extending Prometheus AlertManager
Understanding and Extending Prometheus AlertManagerLee Calcote
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAhsanul Karim
 

Similaire à BroadcastReceivers in Android (20)

Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsAndroid App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgets
 
Android App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsAndroid App Development - 14 location, media and notifications
Android App Development - 14 location, media and notifications
 
Android broadcast receiver tutorial
Android broadcast receiver   tutorialAndroid broadcast receiver   tutorial
Android broadcast receiver tutorial
 
Android Application Components-BroadcastReceiver_Content Provider.pptx
Android Application Components-BroadcastReceiver_Content Provider.pptxAndroid Application Components-BroadcastReceiver_Content Provider.pptx
Android Application Components-BroadcastReceiver_Content Provider.pptx
 
Android Training (Broadcast Receiver)
Android Training (Broadcast Receiver)Android Training (Broadcast Receiver)
Android Training (Broadcast Receiver)
 
Exercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone callExercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone call
 
Android appwidget
Android appwidgetAndroid appwidget
Android appwidget
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
 
Skinning Android for Embedded Applications
Skinning Android for Embedded ApplicationsSkinning Android for Embedded Applications
Skinning Android for Embedded Applications
 
Introduction toandroid
Introduction toandroidIntroduction toandroid
Introduction toandroid
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
 
Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...
 
Londroid Android Home Screen Widgets
Londroid Android Home Screen WidgetsLondroid Android Home Screen Widgets
Londroid Android Home Screen Widgets
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
Android应用开发简介
Android应用开发简介Android应用开发简介
Android应用开发简介
 
Android Froyo
Android FroyoAndroid Froyo
Android Froyo
 
Understanding and Extending Prometheus AlertManager
Understanding and Extending Prometheus AlertManagerUnderstanding and Extending Prometheus AlertManager
Understanding and Extending Prometheus AlertManager
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver Tutorial
 
Integrando sua app Android com Chromecast
Integrando sua app Android com ChromecastIntegrando sua app Android com Chromecast
Integrando sua app Android com Chromecast
 

BroadcastReceivers in Android

  • 1. Broadcast Receivers in Android Perfect APK
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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.