ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP4124Displaying Notificatio…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP4124

    Mobile Application Development 1

    Progress0 / 33 done
    Topics33
    1Mobiles Application Development Platform2HTML5 for Mobiles
    3Architecture, Framework and Application Development
    4Architecture, Framework5Application Development with Windows Mobile6Eclipse7Fragments8Calling Built-in Applications using Intents9Displaying Notifications10Components of a Screen11Adapting to Display Orientation12Managing Changes to Screen Orientation13Utilizing the Action Bar14Creating the User Interface15Listening for UI Notifications16Views17User Preferences18Persisting & Sharing Data19Sending SMS Messages20Getting Feedback21Sending E-mail22Displaying Maps23Consuming Web Services Using HTTP
    24Accessing and Creating25Threading26Publishing Android Applications27Deployment on App Stores28Mobile Programming Languages29Challenges with Mobility and Wireless Communication30Location-aware Applications31Performance/Power Tradeoffs32Mobile Platform Constraints33Emerging Technologies
    6 min read
    Topic 9 of 33
    Topic Study Note Illustration
    09

    Displaying Notifications

    Notifications are a core feature in mobile apps that allow developers to communicate with users, even when the app is not actively in use. They help provide...

    Displaying Notifications in Mobile Applications

    Notifications are a core feature in mobile apps that allow developers to communicate with users, even when the app is not actively in use. They help provide important information, reminders, alerts, updates, or even promotions, ensuring users remain engaged with the app. There are different types of notifications, including local notifications (triggered by the app itself) and push notifications (sent remotely from a server). Below is an overview of how to implement and manage notifications effectively in mobile apps.


    Types of Notifications

    1. Local Notifications

    • Definition: Local notifications are triggered by the app itself, based on actions or time-related events within the app. They do not require an internet connection and are set up and managed locally on the device.
    • Use Cases: Reminders, alarms, timers, or alerts based on app-specific conditions (like a countdown or scheduled event).
    • Example: A fitness app sending a reminder to the user to work out at a scheduled time.

    2. Push Notifications

    • Definition: Push notifications are messages sent from a remote server to a user’s device. These messages can appear even if the user is not actively using the app. Push notifications are commonly used for updates, breaking news, and promotional messages.
    • Use Cases: News alerts, social media updates, chat messages, or promotional offers.
    • Example: An e-commerce app sending a notification about a sale, even if the user is not currently in the app.

    Setting Up Notifications

    1. Local Notifications

    For Android

    To set up local notifications on Android, you would generally use the NotificationManager class to create and manage notifications. Here's how you can implement it:

    • Create a Notification:

      NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      
      NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "your_channel_id")
          .setSmallIcon(R.drawable.notification_icon)
          .setContentTitle("Reminder")
          .setContentText("Don't forget your workout!")
          .setPriority(NotificationCompat.PRIORITY_DEFAULT);
      
      notificationManager.notify(1, builder.build());
      
    • Setting up Notification Channels (for Android 8.0 and above):

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          CharSequence name = "Channel Name";
          String description = "Channel Description";
          int importance = NotificationManager.IMPORTANCE_DEFAULT;
          NotificationChannel channel = new NotificationChannel("your_channel_id", name, importance);
          channel.setDescription(description);
      
          NotificationManager notificationManager = getSystemService(NotificationManager.class);
          notificationManager.createNotificationChannel(channel);
      }
      
    For iOS

    In iOS, you use the UNNotificationRequest and UNNotificationCenter classes to schedule and manage notifications:

    • Request Permission:

      UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
          if granted {
              print("Permission granted")
          } else {
              print("Permission denied")
          }
      }
      
    • Schedule a Notification:

      let content = UNMutableNotificationContent()
      content.title = "Reminder"
      content.body = "Time to work out!"
      content.sound = UNNotificationSound.default
      
      let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
      
      let request = UNNotificationRequest(identifier: "workoutReminder", content: content, trigger: trigger)
      
      UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
      

    2. Push Notifications

    For Android
    • Firebase Cloud Messaging (FCM) is the recommended service for sending push notifications in Android apps. It allows sending notifications from a backend server to user devices.

      • Add Firebase to your Android project:

        1. Add Firebase to your Android project via Firebase Console.
        2. Add the Firebase SDK to your build.gradle file.
      • Send Push Notification from the Server: The server sends a push notification request to Firebase Cloud Messaging (FCM) API. Here's an example of sending a message from the server:

        {
            "to": "user_device_token",
            "notification": {
                "title": "New Message",
                "body": "You have received a new message!"
            }
        }
        
      • Handle the Push Notification in Android: You can override the onMessageReceived() method in FirebaseMessagingService to process incoming notifications:

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            if (remoteMessage.getNotification() != null) {
                String title = remoteMessage.getNotification().getTitle();
                String body = remoteMessage.getNotification().getBody();
                
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "your_channel_id")
                    .setSmallIcon(R.drawable.notification_icon)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        
                NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
                notificationManager.notify(0, notificationBuilder.build());
            }
        }
        
    For iOS
    • Apple Push Notification Service (APNs) is used to send push notifications to iOS devices.

      • Request Permission:

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if granted {
                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }
        }
        
      • Sending Push Notification: Push notifications are sent to the device through APNs from your backend server. The server sends a request to the APNs service with the necessary payload, including the message and the device token.

      • Handle Push Notification: In your AppDelegate.swift, implement the method to handle notifications:

        func application(_ application: UIApplication, didReceiveRemoteNotification notification: [AnyHashable: Any]) {
            if let aps = notification["aps"] as? [String: AnyObject],
               let alert = aps["alert"] as? [String: AnyObject],
               let body = alert["body"] as? String {
                print("Push Notification: $$body)")
            }
        }
        

    Best Practices for Displaying Notifications

    1. Provide Value

    • Notifications should provide useful information and not be overly frequent or intrusive. For example, only notify users about essential updates or actions they need to take, like an appointment reminder or a message alert.

    2. Allow User Control

    • Let users control the types of notifications they receive (e.g., via app settings), and allow them to disable notifications completely if they wish. For example, users should be able to enable or disable sound or choose which type of notifications they want to receive.

    3. Include Clear and Actionable Content

    • Notifications should have clear titles and actionable content. Provide buttons or options to allow users to interact with notifications directly (e.g., open the app, reply to a message, or dismiss).

    4. Respect User's Privacy

    • Be mindful of sensitive information in notifications. Avoid showing personal data in the notification itself (e.g., private messages, credit card details). Always secure sensitive information with encryption or other security measures.

    5. Use Channels for Android

    • For Android apps targeting Android 8.0 (API level 26) and above, use notification channels to group notifications by type (e.g., one channel for messages, another for promotional offers). This allows users to manage notifications better.

    6. Schedule Notifications Wisely

    • For time-sensitive notifications, such as reminders or alerts, make sure they are scheduled at appropriate times and not too frequent. Avoid sending notifications during off-hours unless they are critical.

    Conclusion

    Notifications are an essential part of mobile applications, helping to keep users informed and engaged. Understanding the different types of notifications (local vs. push) and how to implement them on both Android and iOS platforms is crucial for creating effective communication between the app and the user. By following best practices and respecting user preferences, developers can enhance the user experience and keep users coming back to their apps.

    ← Previous topic 8
    Calling Built-in Applications using Intents
    Next topic 10 →
    Components of a Screen

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    6mremaining
    1.1kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Mobile Application Development 1