Table of contents

Quick Summary:

Android 13+ introduced a new runtime permission (POST_NOTIFICATIONS), requiring explicit user consent for notifications. This blog by Creole Studios explores the challenges React Native developers face and presents a robust solution using both JavaScript and native Android code. By modifying MainActivity.java and integrating react-native-permissions and Firebase messaging, developers can ensure seamless notification functionality across all Android versions. Stay ahead of platform updates and optimize your app’s performance with Creole Studios’ expertise in React Native development.

Introduction

In today’s mobile landscape, seamless notifications are essential for user engagement. However, with Android 13+ introducing new runtime permission requirements, React Native developers face challenges in ensuring notifications work as expected. As a leading React Native app development company, Creole Studios stays ahead of platform updates to deliver optimized solutions. This blog explores how Android’s POST_NOTIFICATIONS permission impacts React Native apps and provides a step-by-step approach to handling it efficiently across all Android versions.

The Problem

With Android 13, a new runtime permission, POST_NOTIFICATIONS, mandates explicit user approval before notifications can be displayed. Even if the permission is declared in the AndroidManifest.xml file, the system does not automatically prompt the user to grant it. This led to a significant challenge where notifications were not functioning correctly on Android 13+ devices.

Here is the initial permission declaration added in AndroidManifest.xml:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

Despite this declaration, the JavaScript code for requesting notification permissions was only effective for Android versions below 13 and iOS. On Android 13+, the permission prompt did not appear, preventing the app from obtaining the necessary permissions.

Initial JavaScript Code:

import { check, PERMISSIONS, request } from "react-native-permissions";
import messaging from "@react-native-firebase/messaging";
const requestNotificationPermission = async () => {
  if (Platform.OS === "android") {
    try {
      await request(PERMISSIONS.ANDROID.POST_NOTIFICATIONS)
        .then(() => {
          getToken();
        })
        .catch((err) => {
          console.error(err);
        });
    } catch (error) {
      console.error(error);
    }
  } else if (Platform.OS === "ios") {
    messaging()
      .requestPermission()
      .then(() => {
        getToken();
      })
      .catch((error) => {
        console.error(error);
      });
  }
};

While this approach worked well for iOS and older Android versions, it was ineffective for Android 13+ due to the updated permission requirements.

The Solution

After extensive research and testing, Creole Studios implemented a native Android solution that explicitly requests the POST_NOTIFICATIONS permission at runtime for Android 13+ devices. This was achieved by modifying the MainActivity.java file.

Step 1: Update AndroidManifest.xml

Ensure the required permission is included in AndroidManifest.xml:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

Without this declaration, the app cannot request notification permissions.

Step 2: Modify MainActivity.java

The key component of the solution involves handling permission requests in MainActivity.java explicitly. Below is the added code:

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends ReactActivity {
  private static final int REQUEST_NOTIFICATION_PERMISSION = 1;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Request notification permission for Android 13+
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
      requestNotificationPermission();
    }
  }
  private void requestNotificationPermission() {
    if (ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.POST_NOTIFICATIONS
        ) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
            this,
            new String[]{Manifest.permission.POST_NOTIFICATIONS},
            REQUEST_NOTIFICATION_PERMISSION
        );
    }
  }
  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_NOTIFICATION_PERMISSION) {
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // Permission granted
      } else {
        // Permission denied
      }
    }
  }
}

This implementation ensures that Android 13+ devices explicitly request notification permissions at runtime, aligning with the platform’s updated security policies.

Step 3: Install Required Packages

To support notification permissions, the following dependencies are required:

npm install react-native-permissions
npm install @react-native-firebase/messaging

Step 4: Integrate React Native Code for Cross-Platform Compatibility

To integrate both the JavaScript and native Android solutions seamlessly, the following React Native code can be used:

import React from "react";
import { Platform } from "react-native";
import { check, PERMISSIONS, RESULTS } from "react-native-permissions";
import messaging from "@react-native-firebase/messaging";
const App = () => {
  React.useEffect(() => {
    checkPermission();
  }, []);
  const checkPermission = async () => {
    if (Platform.OS === "android") {
      check(PERMISSIONS.ANDROID.POST_NOTIFICATIONS)
        .then((result) => {
          switch (result) {
            case RESULTS.DENIED:
              requestNotificationPermission();
              break;
            case RESULTS.GRANTED:
              console.log("Permission granted");
              break;
          }
        })
        .catch((error) => {
          console.log(error);
        });
    } else {
      const authStatus = await messaging().requestPermission();
      const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;
      if (!enabled) {
        requestNotificationPermission();
      }
    }
  };
  return null;
};
export default App;

Key Takeaways

  • Android 13 introduced a new runtime permission for notifications, requiring explicit user consent.
  • Adding POST_NOTIFICATIONS in AndroidManifest.xml alone is insufficient.
  • A combination of React Native code and native Android code provides a comprehensive solution for handling notification permissions effectively.

Final Thoughts

Staying updated with platform-specific changes is crucial for ensuring seamless app functionality. By implementing this solution, Creole Studios has successfully addressed the notification permission challenges in Android 13+, ensuring a smooth user experience across different Android versions.For businesses looking to develop robust React Native applications, Creole Studios specializes in tackling such challenges with innovative solutions. Feel free to reach out to discuss how we can optimize your mobile app’s performance and functionality.


Mobile
React Native
Yash Nayi
Yash Nayi

Software Engineer

Launch your MVP in 3 months!
arrow curve animation Help me succeed img
Hire Dedicated Developers or Team
arrow curve animation Help me succeed img
Flexible Pricing
arrow curve animation Help me succeed img
Tech Question's?
arrow curve animation
creole stuidos round ring waving Hand
cta

Book a call with our experts

Discussing a project or an idea with us is easy.

client-review
client-review
client-review
client-review
client-review
client-review

tech-smiley Love we get from the world

white heart