Notification based Android interview questions and answers
Here we have to create an application that schedules a task and send a notification. For that, we need to execute a particular job daily at a specific time defined by the user. We can do it using the AlarmManager in android. Android has a built-in AlarmManager class which makes scheduling tasks. AlarmManager provides access to system-level alarm services. This gives a way to perform any operations outside the lifetime of your application. So we can trigger events or actions even when your application is not running. Step to schedule task is mentioned below:
- We need a Broadcast Receiver to fire the alarm when our app is not running.
- We also need to register this BroadcastReceiver in the Manifest file.
- For Setting Alarm using Alarm Manager Class we will declare a PendingIntent and an AlarmManager variable In Activity.java. The PendingIntent will be used to set and cancel the alarms.
- We used the setRepeating() method to set up a recurring alarm.
Please find below code for more detail:
// check task is scheduled or not boolean alarmUp = (PendingIntent.getBroadcast(this, 0, new Intent("com.example.dummy.AlarmReceiver"), PendingIntent.FLAG_NO_CREATE) != null); if ( !alarmUp) { Intent intent = new Intent("com.example.dummy.AlarmReceiver"); intent.putExtra("activate", true); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); AlarmManager alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 7); calendar.set(Calendar.MINUTE, 0); alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE); PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent2);
What is NotificationManager class?
A) The NotificationManager class is used to display notifications on the device’s status bar
To display a notification on upper left of Android screen, which of the following class you need to use?
A) NotificationManager + Notification
You need to process when user clicks on a notification on upper left of Android screen?
A) PendingIntent
Which is the method you need to use to post a notification to be shown in the status bar?
A) notify(…)
Comments
Post a Comment