Presentation is loading. Please wait.

Presentation is loading. Please wait.

Mobile Programming Broadcast Receivers.

Similar presentations


Presentation on theme: "Mobile Programming Broadcast Receivers."— Presentation transcript:

1 Mobile Programming Broadcast Receivers

2 Broadcasts in Android

3 Broadcasts in Android Broadcasts are messages sent by Android system and other Android apps, when an event of interest occurs. Broadcasts are wrapped in an Intent object. This Intent object’s contains the event details such as, action “android.intent.action.HEADSET_PLUG” is sent when a wired headset is plugged or unplugged. Some other examples are: android.intent.action.BATTERY_CHANGED:broadcast containing the charging state, level, and other information about the battery. android.intent.action.BATTERY_LOW:Indicates low battery condition on the device. android.intent.action.BOOT_COMPLETED :This is broadcast once, after the system has finished booting. android.intent.action.DATE_CHANGED : The date has changed android.net.conn.CONNECTIVITY_CHANGE : The mobile network or wifi connection is changed(or reset) android.provider.Telephony.SMS_RECEIVED: if an sms is received.

4 Types of broadcast: System broadcast Custom broadcast
System broadcast are the messages sent by the Android system, when a system event occurs, that might affect your app. Few examples: An Intent with action, ACTION_BOOT_COMPLETED is broadcasted when the device boots. An Intent with action, ACTION_POWER_CONNECTED is broadcasted when the device is connected to the external power. Screen turning off, battery low, picture was captured, SMS is received Custom broadcast Custom broadcasts are broadcasts that your app sends out, similar to the Android system. For example, when you want to let other app(s) know that some data has been downloaded by your app, and its available for their use.

5 Sending a Custom Broadcast

6 Send a Custom Broadcast
Syntax for sending a custom broadcast intent Intent intent = new Intent(); intent.setAction("com.mp.CUSTOM_INTENT"); sendBroadcast(intent);

7 Broadcast Receivers

8 Broadcast Receivers Broadcast receivers are app components.
They register for various system broadcast and or custom broadcast. They are notified (via an Intent): By the system, when a system event occurs that your app is registered for. By another app, including your own if your app is registered for that custom event.

9 How to implement a Broadcast Receiver
Create a subclass of Android’s BroadcastReceiver Implement the onReceive() method Register that broadcast receiver for a Broadcast Intent

10 Create a subclass of Android’s BroadcastReceiver
public class MyReceiver extends BroadcastReceiver { public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_SHORT).show(); } Following are the two arguments of the onReceive() method: Context: This is used to access additional information, or to start services or activities. Intent: The Intent object is used to register the receiver.

11 Register for listening to a Broadcast Intent
Broadcast receivers can be registered in two ways: Static receivers Registered in your AndroidManifest.xml, also called as Manifest-declared receivers. You do this if your app offers some kind of service around these events even when it is not open Dynamic receivers Registered using app or activities' context in your Java files, also called as Context- registered receivers. You register receivers like this if your app wants to react to state changes

12 Contd. Static Receiver Registration
Dynamic Receiver Registration in onCreate() or onResume() Unregister Receiver in onDestroy() or onPause() <receiver android:name=".MyReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> IntentFilter filter = new IntentFilter(); filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); MyReceiver myReceiver = new MyReceiver(); registerReceiver(myReceiver, filter); @Override protected void onPause() { unregisterReceiver(myReceiver); super.onPause(); }

13 What are Intent Filters
Intent-filters specify the types of intents a broadcast receiver can receive. They filter the incoming intents based on the Intent values like action. To add an intent-filter: To your AndroidManifest.xml file, use <intent-filter> tag. To your Java file use the IntentFilter object.

14 Registration Restrictions
Starting from Android 8.0 (API level 26), static receivers can't receive most of the system broadcasts. Use a dynamic receiver to register for these broadcasts. If you register for the system broadcasts in the manifest, the Android system won't deliver them to your app. A few broadcasts, are excepted from this restriction. See the complete list of implicit broadcast exceptions.

15 Example Code – Creating a broadcast receiver that listens to network change events
<manifest xmlns:android=" package="com.lab.pdoffice.systembroadcastapp"> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:supportsRtl="true" <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".ConnectionReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> </application> </manifest>

16 Contd. Broadcast Receiver
public class ConnectionReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if (isConnected) { Toast.makeText(context, "Network is connected", Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, "Network is changed or reconnected", Toast.LENGTH_LONG).show(); } } }

17 Example Code 2 - Creating a broadcast receiver that listens to custom broadcasts
public class MainActivity extends AppCompatActivity { MyReceiver receiver; IntentFilter intentFilter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); receiver = new MyReceiver(); intentFilter = new IntentFilter("com.mp.customintent"); registerReceiver(receiver,intentFilter); } public void sendCustomBroadcast(View v){ Intent i = new Intent("com.mp.customintent"); sendBroadcast(i); } @Override protected void onDestroy() { unregisterReceiver(receiver); super.onDestroy(); } } <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android=" xmlns:app=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send Broadcast!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" android:onClick="sendCustomBroadcast"/> </android.support.constraint.ConstraintLayout>

18 Contd. Broadcast Receiver
public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction()=="com.mp.customintent") { Toast.makeText(context, "custom intent received", Toast.LENGTH_LONG).show(); } }

19 Thank You!


Download ppt "Mobile Programming Broadcast Receivers."

Similar presentations


Ads by Google