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›Listening for UI Notifications
    Mobile Application DevelopmentTopic 15 of 33

    Listening for UI Notifications

    8 minread
    1,288words
    Intermediatelevel

    Listening for UI Notifications in Mobile Applications

    In mobile app development, it’s important to be able to listen for and respond to various user interface (UI) notifications or events. These events can be user interactions like button clicks, text input changes, or system-generated notifications like background tasks completing or connectivity status changes. Handling these events ensures the app is responsive and dynamic.

    In both Android and iOS development, there are methods for detecting UI changes, listening to user interactions, and handling system notifications. Let’s break down how this is typically done.


    Android: Listening for UI Notifications

    In Android, UI notifications generally refer to user-triggered events or system messages that the app needs to respond to. These notifications are often tied to user actions or system changes.

    1. Listening for Button Clicks (Event Handlers)

    In Android, the most basic form of UI interaction is responding to button clicks. This can be done through setting OnClickListener on buttons:

    Button submitButton = findViewById(R.id.submitButton);
    submitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Action to be performed when the button is clicked
            Toast.makeText(MainActivity.this, "Button clicked!", Toast.LENGTH_SHORT).show();
        }
    });
    

    In this example, when the user clicks the button, the app will show a Toast message, indicating that the button was clicked.

    2. Listening for Text Changes (TextWatcher)

    If you want to listen for changes to a text field (e.g., EditText), you can use the TextWatcher interface. This is useful for real-time validation or responding to user input.

    EditText usernameEditText = findViewById(R.id.username);
    usernameEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
            // Handle any changes before the text is changed
        }
    
        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            // This is where you can act on real-time input change
        }
    
        @Override
        public void afterTextChanged(Editable editable) {
            // Handle text after change
            String input = editable.toString();
            if(input.length() > 5) {
                // Perform an action (e.g., enable button)
            }
        }
    });
    

    Here, the afterTextChanged() method listens for changes to the text in the EditText field and responds when the text changes.

    3. Listening for System Notifications (BroadcastReceiver)

    Android allows apps to listen for system-wide events or notifications like network connectivity changes, battery status changes, or other system-level events using a BroadcastReceiver. For example, you can listen for changes in network connectivity:

    // Registering the receiver in the Activity or Application
    BroadcastReceiver networkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Check the network status and handle it
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null && activeNetwork.isConnected();
            
            if (isConnected) {
                // Do something when connected
            } else {
                // Handle disconnected state
            }
        }
    };
    
    // Create an IntentFilter to catch the connectivity changes
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(networkReceiver, filter);
    

    This BroadcastReceiver listens for connectivity changes and can take action based on whether the device is connected to the internet.

    4. Listening for Touch Events (OnTouchListener)

    You can also listen for touch events, such as when a user taps or swipes on the screen. The OnTouchListener allows you to capture touch interactions.

    View touchView = findViewById(R.id.touchView);
    touchView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                // Action when the screen is touched
                Toast.makeText(MainActivity.this, "View touched", Toast.LENGTH_SHORT).show();
                return true;
            }
            return false;
        }
    });
    

    In this example, the app listens for when the user touches the View (e.g., a button, image, or layout), and the app will show a message.

    5. Listening for UI Notifications Using LiveData (Architecture Component)

    If you are using Android Architecture Components, you can listen for UI updates in a lifecycle-conscious way using LiveData. This helps ensure that your app responds to changes while respecting the lifecycle of activities and fragments.

    // Inside your ViewModel
    private MutableLiveData<String> userMessage = new MutableLiveData<>();
    
    // Inside your Activity or Fragment
    userViewModel.getUserMessage().observe(this, new Observer<String>() {
        @Override
        public void onChanged(String message) {
            // Update UI when the message changes
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
        }
    });
    

    Here, LiveData is used to observe changes to the userMessage and update the UI automatically when the value changes.


    iOS: Listening for UI Notifications

    In iOS, the process of responding to UI notifications and user interactions is similar, though the implementation uses different concepts. In iOS, we commonly use delegates, target-action patterns, or NotificationCenter to listen for events and respond accordingly.

    1. Listening for Button Clicks (Target-Action)

    In iOS, you often use the target-action pattern to listen for events like button clicks. For example:

    let submitButton = UIButton(type: .system)
    submitButton.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
    
    @objc func buttonClicked() {
        // Handle button click
        print("Button clicked!")
    }
    

    In this code, the addTarget() method is used to listen for a button click event and call the buttonClicked() method when the event occurs.

    2. Listening for Text Changes (TextField Delegate)

    To listen for text changes in UITextField, you can use the UITextFieldDelegate protocol. Here's how you can handle text change notifications:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // Respond to text input change
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if newText.count > 5 {
            // Do something (e.g., enable a button)
        }
        return true
    }
    

    In this case, the delegate method shouldChangeCharactersIn is called each time the user types in the text field, allowing the app to respond to text changes in real time.

    3. Listening for System Notifications (NotificationCenter)

    To listen for system-wide events like application state changes, connectivity status, or other system notifications, iOS uses NotificationCenter. For example, to listen for when the app enters the background:

    NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    
    @objc func appDidEnterBackground() {
        // Handle app entering the background
        print("App entered background")
    }
    

    This code listens for the didEnterBackgroundNotification, which is triggered when the app moves to the background, and calls the appDidEnterBackground() method.

    4. Listening for Touch Events (Gesture Recognizers)

    In iOS, you can use Gesture Recognizers to listen for touch interactions like taps, swipes, or pinches:

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
    view.addGestureRecognizer(tapGesture)
    
    @objc func handleTap() {
        // Handle tap event
        print("View tapped!")
    }
    

    In this example, a tap gesture recognizer is added to a view, and the handleTap() method is called whenever the user taps on the view.

    5. Listening for UI Notifications Using Combine (iOS 13+)

    In iOS 13 and later, the Combine framework provides a reactive approach to handling UI notifications and updates. Here’s an example of observing changes using Combine:

    import Combine
    
    var cancellable: AnyCancellable?
    
    cancellable = $userMessage.sink { message in
        // Update UI when the message changes
        print("User message: $$message)")
    }
    

    Here, the userMessage is a @Published property, and the Combine framework automatically updates the UI when userMessage changes.


    Conclusion

    Listening for UI notifications is essential for creating interactive, responsive, and dynamic mobile apps. Whether it’s responding to button clicks, text changes, system-level events, or user gestures, both Android and iOS provide mechanisms to detect and handle these events.

    • In Android, this can be done with listeners such as OnClickListener, TextWatcher, BroadcastReceiver, and LiveData.
    • In iOS, you can use target-action, delegates, NotificationCenter, and Gesture Recognizers.

    By effectively handling these UI notifications, you can ensure your app provides a seamless and engaging user experience.

    Previous topic 14
    Creating the User Interface
    Next topic 16
    Views

    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 time8 min
      Word count1,288
      Code examples0
      DifficultyIntermediate