ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development
    EC-333
    Progress0 / 33 topics
    Topics
    1. Mobiles Application Development Platform2. HTML5 for Mobiles3. Android OS: Architecture, Framework and Application Development4. iOS: Architecture, Framework5. Application Development with Windows Mobile6. Eclipse7. Fragments8. Calling Built-in Applications using Intents9. Displaying Notifications10. Components of a Screen11. Adapting to Display Orientation12. Managing Changes to Screen Orientation13. Utilizing the Action Bar14. Creating the User Interface15. Listening for UI Notifications16. Views17. User Preferences18. Persisting & Sharing Data19. Sending SMS Messages20. Getting Feedback21. Sending E-mail22. Displaying Maps23. Consuming Web Services Using HTTP24. Web Services: Accessing and Creating25. Threading26. Publishing Android Applications27. Deployment on App Stores28. Mobile Programming Languages29. Challenges with Mobility and Wireless Communication30. Location-aware Applications31. Performance/Power Tradeoffs32. Mobile Platform Constraints33. Emerging Technologies
    EC-333›Displaying Notifications
    Mobile Application DevelopmentTopic 9 of 33

    Displaying Notifications

    6 minread
    1,077words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,077
      Code examples0
      DifficultyIntermediate