Download presentation
Presentation is loading. Please wait.
1
SMB - BroadcastReceiver and notifications
Michail Mokkas
2
Broadcast Receiver A component that allows logging to application or system events. As soon as a given event occurs, all "receivers" registered to it will get notified and will be able to take action. It also often serves as a kind of communication between several different applications or within one application.
3
Broadcast Receiver kont. 1
The receiver can be registered in two ways : Static: via the use of AndroidManifest.xml . From Oreo, restrictions on static registration have been added to reduce background processes. Dynamic: via the use of the method: Should be unregistered if it's no longer needed: unregisterReceiver(receiver); <receiver android:name="MyBroadcastReceiver“> <intent-filter> <action android:name="com.example.MY_CUSTOM_INTENT“/> </intent-filter> </receiver> registerReceiver(MyBroadcastReceiver mbr, new IntentFilter("com.example.MY_CUSTOM_INTENT"));
4
Example of dynamic registration
public class MainActivity extends Activity { public static final String myIntent = "com.example.smb.myapplication.intent.action.EVENT1"; private MyBroadcastReceiver mbr = new MyBroadcastReceiver(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart(){ super.onStart(); registerReceiver(mbr, new IntentFilter(myIntent)); } @Override protected void onStop(){ super.onStop(); unregisterReceiver(mbr); } }
5
Example of static registration
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.might.myapplication"> <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> <activity android:name=".OptionsActivity"></activity> <receiver android:name="MyBroadcastReceiver"> <intent-filter> <action android:name="com.example.MY_CUSTOM_INTENT“/> </intent-filter> </receiver> </application> </manifest>
6
Broadcast Receiver cont. 2
System broadcasts: android.intent.action.BOOT_COMPLETED android.intent.action.BATTERY_LOW android.intent.action.SCREEN_OFF android.net.wifi.STATE_CHANGE android.provider.Telephony.SMS_RECEIVED android.provider.Telephony.SIM_FULL It is possible to create custom ones. The entire list of available system broadcasts can be found in the file: /sdk/platforms/android-XX/data/broadcast_actions.txt
7
Types of broadcasts Broadcast types:
Normal: all receivers perform actions at the same time (when they receive the broadcast intention). Ordered: broadcasts are sent to one receiver. After completing his performed broadcast actions is forwarded to the next along with the result of the actions taken. Each of the receivers can complete the process preventing subsequent actions. The order is determined by the android:priority attribute of the intent filter.
8
Receiver priority The order in which receivers receive ordered broadcasts depends on the priority value. It is set using the parameter android:priority (static) or using the IntentFilter.setPriority() method (dynamic). The value should be in the range: minimum: IntentFilter.SYSTEM_LOW_PRIORITY -1000 maximum: IntentFilter.SYSTEM_HIGH_PRIORITY 1000 default: 0
9
Receiver priority cont. 1
Static Dynamic <receiver android:name="MyBroadcastReceiver"> <intent-filter android:priority="999"> <action android:name="com.example.smb.myapplication.intent.action.EVENT1“/> </intent-filter> </receiver> @Override protected void onStart(){ super.onStart(); IntentFilter if1 = new IntentFilter(myIntent); if1.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY-1); registerReceiver(mbr, if1); }
10
Types of broadcasts cont. 1
Broadcast types: Sticky Intent: the intent is stored after it is broadcasted. New Intents overwrite old ones. With dynamic registration of the receiver, all stored Intents that match its filter are sent to it. Along with API 21, it was deprecated because it posed a security risk. Non-Sticky Intent: the Intent is deleted when it is broadcasted. Using permissions or not.
11
Types of broadcasts cont. 2
Intent broadcasting: private void onClick(View v){ Intent intent1 = new Intent(myIntent); String permission1 = Manifest.permission.READ_SMS; //normal broadcast sendBroadcast(intent1); //ordered broadcast sendOrderedBroadcast(intent1, permission1); //ordered broadcast sendOrderedBroadcast(intent1, permission1, new BroadcastReceiver(){ public void onReceive(Context context, Intent intent){ Toast.makeText(context, "Result:"+getResultData(), Toast.LENGTH_LONG).show(); } },null, 0, null, null); //handler, initiatlCode, initialData, initialExtras }
12
Broadcast Receiver cont. 3
Life cycle: The BroadcastReceiver object is considered valid from the beginning to the end of the onReceive() method For this reason, we cannot perform any asynchronous actions that, when completed, would return the result to the now inactive BroadcastReceiver (killed by the system). From API 11 you can use the goAsync() method We cannot register for service binding or show dialogs from it. An alternative to dialogs can be notifications created using the NotificationManager. The process that performs our receiver is considered to be of high priority/importance.
13
Permission to receive broadcasts
In order to prevent the acceptance of broadcasted Intents from all applications and to accept only selected ones, it is possible to create permissions that these applications should have. The alternative is: setting the parameter of the BR in AndroidManifest.xml: android:exported = "false" creation of LocaLBroadcastManager (listens only for actions from the same process)
14
Permissions cont. 1 In order to create our own permission in AndroidManifest.xml : In <receiver> we add: <permission-group android:name="com.example.my_permissions" android:label="my permissions group" /> <permission android:name="com.example.my_permissions.MY_PERMISSION" android:permissionGroup="com.examples.my_permissions" android:label="my permission"/> <uses-permission android:name="com.example.my_permissions.MY_PERMISSION" /> <receiver android:name="MyBroadcastReceiver" android:permission="com.example.my_permissions.MY_PERMISSION"> <intent-filter> <action android:name="com.example.smb.myapplication.intent.action.EVENT1“ /> </intent-filter> </receiver>
15
Starting the receiver in a separate process
In order to start the receiver in a separate process, you can use the android: process parameter. This means that the receiver will not be dependent on the operation of our application. <receiver android:name="MyBroadcastReceiver" android:process=":remote"> <intent-filter> <action android:name="com.example.smb.myapplication.intent.action.EVENT1"> </action> </intent-filter> </receiver>
16
Example: broadcasting an Intent
Creation: In our Activity we add: In the layout of the Activity we add: public void broadcastIntent(View view){ Intent intent = new Intent(); intent.setAction("com.example.MY_CUSTOM_INTENT"); sendBroadcast(intent); } <Button android:onClick="broadcastIntent" android:layout_width="match_parent" android:layout_height="wrap_content" />
17
Example of a receiver Creation:
public class MyBroadcastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent){ Toast.makeText(context, "Intent received.", Toast.LENGTH_LONG).show(); } }
18
Example of a receiver cont. 1
Forwarding of the result. public class Receiver1 extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent){ String tmp = getResultData(); setResultData(tmp+"Data from receiver1"); } }
19
Example of a receiver cont. 2
Cancelling of additional broadcasting. public class Receiver2 extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent){ if(isOrderedBroadcast()){ abortBroadcast(); } Toast.makeText(context, "Intent received.", Toast.LENGTH_LONG).show(); } }
20
Example of a receiver cont. 3
In AndroidManifest.xml file inside <application> tag : <receiver android:name="MyBroadcastReceiver" > <intent-filter> <action android:name="com.example.MY_CUSTOM_INTENT" /> </intent-filter> </receiver>
21
Result of example (1)
22
Example 2 Starting a Service after system boot:
public class MyBroadcastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent){ Intent service_intent = new Intent(context, MyService.class); context.startService(service_intent); } }
23
Example 2 cont.1 Manifest:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.might.myapplication"> <users-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <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> <activity android:name=".OptionsActivity"></activity> <receiver android:name="MyBroadcastReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> </application> </manifest>
24
PackageManager We can use PackageManager to turn off some statically registered receiver after catching the intention once and executing the onReceive() method. PackageManager pm = getPackageManager(); ComponentName cn = new ComponentName(getApplicationContext(), MyBroadcastReceiver.class); pm.setComponentEnabledSetting(cn, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
25
PackageManager cont. 1 States that can be used are :
COMPONENT_ENABLED_STATE_DEFAULT - state as described in AndroidManifest.xml . COMPONENT_ENABLED_STATE_DISABLED - disabled. COMPONENT_ENABLED_STATE_ENABLED - enabled. Changing the status of a component can make the application behavior unpredictable. In this situation, the DONT_KILL_APP flag prevents the system from closing the application.
26
PendingIntent They are a kind of tokens that an application can pass to another application, thus enabling it to receive the first permission to perform some commands. In order to obtain PendingIntent we have to use one of the methods: PendingIntent.getActivity() - to run the activity. PendingIntent.getBroadcast() - for broadcast. PendingIntent.getService() - to start the service. Invalidated using the cancel() method.
27
Pending Intent cont. 1 Arguments of get[Activity/Broadcast/Service]() methods: Context - application context requestCode - the private query code for obtaining the same pending intent in the future (e.g. to cancel using the cancel() method) intent - explicit Intent of the activity to be launched flag - flag: FLAG_CANCEL_CURRENT - if pending intent already exists then the existing one should be canceled before creating a new one. FLAG_IMMUTABLE - pending intent should not change. FLAG_NO_CREATE - if pending intent does not exist then return null instead of creating a new one. FLAG_ONE_SHOT - this pending intent can only be used once. FLAG_UPDATE_CURRENT - if pending intent already exists, save it, but replace its data (extra data) with those from the new one.
28
Notifications The Android system allows to display notifications related to applications on the notification bar (status bar). It is possible to add elements that manage available activities, services etc. image source:
29
NotificationCompat.Builder
Methods of the NotificationCompat.Builder class: setContentTitle() - changes the content of the first line. setContentText() - changes the content of the second line. setSmallIcon() - sets the image that will be visible in it (left). setContentIntent() - sets the pending intent that is sent when the notification is clicked. setAutoCancel() - notification disappears when you click it. build() - creates a notification.
30
NotificationManager The class responsible for notifying the user about events that occur. A way of informing the user about various things that happened in the background. Manages: Notifications (in status bar) LED lights Notification via background lighting, sound firing or vibration The method notify(int id, Notification notification) - publishes the notification in the statusbar (if the identifier is the same, the notifications will overwrite)
31
Creation of a Notification
Creation (in a class extending Activity): private final String channelID = "channel1"; private int id = 0; public void onClick(View view) { Intent intent = new Intent(this, Main2Activity.class); PendingIntent pendint = PendingIntent.getActivity(this, 0, intent, 0); NotificationCompat.Builder notif = new NotificationCompat.Builder(this, channelID) setSmallIcon(R.mipmap.ic_launcher) setContentTitle(getString(R.string.my_title)) setContentText(getString(R.string.my_text)) setContentIntent(pendint) setAutoCancel(true); NotificationManagerCompat nm = NotificationManagerCompat.from(this); nm.notify(id++, notif.build()); }
32
Result
33
Notification channels (API 26+)
Our notification must be assigned to a channel. The user can choose which channels of notifications of our app is interested in, and which to block. Remember to call the method before you display the notification, e.g. in onCreate() (if you are in Activity). //API 26+ private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // SDK >= CharSequence name = getString(R.string.my_channel); String description = getString(R.string.my_chan_desc); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(channelID, name, importance); channel.setDescription(description); NotificationManager nm = getSystemService(NotificationManager.class); nm.createNotificationChannel(channel); } }
34
Example of a custom notification
To create a custom notification we need: MainActivity.java - the main activity class with a button to create notifications. MyNotification.java - an activity class that is launched after clicking the notification. activity_main.xml - MainActivity layout. activity_my_notification.xml - MyNotification layout. myootification.xml - custom notification layout.
35
Example cont. 1 MainActivity.java (part 1)
36
Example cont. 2 MainActivity.java (part 2)
37
Example cont. 3 activity_main.xml
38
Example cont. 4 MyNotification.java
39
Example cont. 5 activity_my_notification.xml
40
Example cont. 6 mojanotyfikacja.xml
41
Result
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.