Paul
Paul

Reputation: 641

Ask permission for push notification

I'm working an application and I need to use push notification. I know that push notification are a normal permission so I can't ask it at run time. But I would insert in the permission when the user downloads and installs the application, and the notice that the application should send a push notification.

How can I do it? Do I have to insert something in the manifest?

Upvotes: 53

Views: 203500

Answers (9)

Rahul Kushwaha
Rahul Kushwaha

Reputation: 6712

You can give permission in Android as folows:-

with(NotificationManagerCompat.from(this)) {
                if (ActivityCompat.checkSelfPermission(
                        this@MainActivity,
                        Manifest.permission.POST_NOTIFICATIONS
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)

                    shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)
                    println("check permission")
                    println(areNotificationsEnabled())
                    return@with
                }
                // notificationId is a unique int for each notification that you must define.
                //notify(NOTIFICATION_ID, builder.build())
            }

Upvotes: 0

Editor Here
Editor Here

Reputation: 121

 int permissionState = ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS);
    // If the permission is not granted, request it.
    if (permissionState == PackageManager.PERMISSION_DENIED) {
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.POST_NOTIFICATIONS}, 1);
    }

Upvotes: 12

Dusan Spasojevic
Dusan Spasojevic

Reputation: 51

I use https://github.com/zoontek/react-native-permissions

import {requestNotifications} from 'react-native-permissions';

await requestNotifications(['alert', 'badge', 'sound']);

and add

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

to androidManifest.xml

Upvotes: 2

Akshay Karande
Akshay Karande

Reputation: 71

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>// add this to menifest file

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        if (ActivityCompat.checkSelfPermission(this,Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
        
            requestPermissions(new String[] {Manifest.permission.POST_NOTIFICATIONS}, 1);

    } 
    else {
      // repeat the permission or open app details
     }
    }

Upvotes: 7

AskNilesh
AskNilesh

Reputation: 69681

Here is the complete example of how can you ask run time permission for notifications in Android 13 (Tiramisu)

First, add the below permission in your manifest file

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

Use the below code to ask for run time permission

package com.example.myapplication

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Color
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
import android.widget.Button
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.NotificationCompat
import com.google.android.material.dialog.MaterialAlertDialogBuilder

class MainActivity : AppCompatActivity() {

    private val notificationPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            hasNotificationPermissionGranted = isGranted
            if (!isGranted) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (Build.VERSION.SDK_INT >= 33) {
                        if (shouldShowRequestPermissionRationale(android.Manifest.permission.POST_NOTIFICATIONS)) {
                            showNotificationPermissionRationale()
                        } else {
                            showSettingDialog()
                        }
                    }
                }
            } else {
                Toast.makeText(applicationContext, "notification permission granted", Toast.LENGTH_SHORT)
                    .show()
            }
        }

    private fun showSettingDialog() {
        MaterialAlertDialogBuilder(this, com.google.android.material.R.style.MaterialAlertDialog_Material3)
            .setTitle("Notification Permission")
            .setMessage("Notification permission is required, Please allow notification permission from setting")
            .setPositiveButton("Ok") { _, _ ->
                val intent = Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.data = Uri.parse("package:$packageName")
                startActivity(intent)
            }
            .setNegativeButton("Cancel", null)
            .show()
    }

    private fun showNotificationPermissionRationale() {

        MaterialAlertDialogBuilder(this, com.google.android.material.R.style.MaterialAlertDialog_Material3)
            .setTitle("Alert")
            .setMessage("Notification permission is required, to show notification")
            .setPositiveButton("Ok") { _, _ ->
                if (Build.VERSION.SDK_INT >= 33) {
                    notificationPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
                }
            }
            .setNegativeButton("Cancel", null)
            .show()
    }

    var hasNotificationPermissionGranted = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<Button>(R.id.btnRequestPermission).setOnClickListener {
            if (Build.VERSION.SDK_INT >= 33) {
                notificationPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
            } else {
                hasNotificationPermissionGranted = true
            }
        }
        findViewById<Button>(R.id.btnShowNotification).setOnClickListener {
            if (checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
                showNotification()
            }
        }
    }

    private fun showNotification() {

        val channelId = "12345"
        val description = "Test Notification"

        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel =
                NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH)
            notificationChannel.lightColor = Color.BLUE

            notificationChannel.enableVibration(true)
            notificationManager.createNotificationChannel(notificationChannel)

        }

        val  builder = NotificationCompat.Builder(this, channelId)
            .setContentTitle("Hello World")
            .setContentText("Test Notification")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    this.resources, R.drawable
                        .ic_launcher_background
                )
            )
        notificationManager.notify(12345, builder.build())
    }
}

If you using jetpack compose then user below code

class MainActivity : ComponentActivity() {

  @RequiresApi(VERSION_CODES.M)
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      JetpackComposeNotifcationPermissionTheme {
        val context = LocalContext.current
        val permissionOpenDialog = remember { mutableStateOf(false) }
        val rationalPermissionOpenDialog = remember { mutableStateOf(false) }

        if (permissionOpenDialog.value) {
          ShowSettingDialog(openDialog = permissionOpenDialog)
        }

        var hasNotificationPermission by remember {
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            mutableStateOf(
              ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.POST_NOTIFICATIONS
              ) == PackageManager.PERMISSION_GRANTED
            )
          } else mutableStateOf(true)
        }

        val launcher = rememberLauncherForActivityResult(
          contract = ActivityResultContracts.RequestPermission(),
          onResult = { isGranted ->
            if (!isGranted) {
              if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
                rationalPermissionOpenDialog.value = true
              } else {
                permissionOpenDialog.value = true
              }
            } else {
              hasNotificationPermission = isGranted
            }
          }
        )
        if (rationalPermissionOpenDialog.value) {
          ShowRationalPermissionDialog(openDialog = rationalPermissionOpenDialog) {
            rationalPermissionOpenDialog.value = false
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
              launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
          }
        }


        Column(
          modifier = Modifier.fillMaxSize(),
          verticalArrangement = Arrangement.Center,
          horizontalAlignment = Alignment.CenterHorizontally
        ) {
          Button(onClick = {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
              launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
          }) {
            Text(text = "Request permission")
          }
          Button(onClick = {
            if (hasNotificationPermission) {
              showNotification()
            }
          }) {
            Text(text = "Show notification")
          }
        }
      }
    }
  }

  private fun showNotification() {
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val channelId = "12345"
    val description = "Test Notification"

    if (VERSION.SDK_INT >= VERSION_CODES.O) {
      val notificationChannel =
        NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH)
      notificationChannel.lightColor = Color.BLUE

      notificationChannel.enableVibration(true)
      notificationManager.createNotificationChannel(notificationChannel)
    }
    val notification = NotificationCompat.Builder(applicationContext, channelId)
      .setSmallIcon(R.drawable.ic_launcher_foreground)
      .setContentTitle("Hello Nilesh")
      .setContentText("Test Notification")
      .build()
    notificationManager.notify(1, notification)
  }

  @Composable
  fun ShowSettingDialog(openDialog: MutableState<Boolean>) {
    if (openDialog.value) {
      AlertDialog(
        onDismissRequest = {
          openDialog.value = false
        },
        title = {
          Text(text = "Notification Permission")
        },
        text = {
          Text("Notification permission is required, Please allow notification permission from setting")
        },

        buttons = {
          Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.End,
            verticalAlignment = Alignment.CenterVertically,
          ) {
            TextButton(
              onClick = {
                openDialog.value = false
              }
            ) {
              Text("Cancel")
            }
            Spacer(modifier = Modifier.width(20.dp))
            TextButton(
              onClick = {
                openDialog.value = false
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.data = Uri.parse("package:$packageName")
                startActivity(intent)
              },
            ) {
              Text("Ok")
            }
          }

        },
      )
    }
  }

  @Composable
  fun ShowRationalPermissionDialog(openDialog: MutableState<Boolean>, onclick: () -> Unit) {
    if (openDialog.value) {
      AlertDialog(
        onDismissRequest = {
          openDialog.value = false
        },
        title = {
          Text(text = "Alert")
        },
        text = {
          Text("Notification permission is required, to show notification")
        },

        buttons = {
          Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.End,
            verticalAlignment = Alignment.CenterVertically,
          ) {
            TextButton(
              onClick = {
                openDialog.value = false
              }
            ) {
              Text("Cancel")
            }
            Spacer(modifier = Modifier.width(20.dp))
            TextButton(
              onClick = onclick,
            ) {
              Text("Ok")
            }
          }

        },
      )
    }
  }
}

Upvotes: 39

Kunal Chawla
Kunal Chawla

Reputation: 1314

UPDATE 2022

The way we request permissions on Android has changed drastically with Android 13. Please see other answers below that mention the same.


As answered here, you don't need permissions for push notifications.

Actually the push notification permission lie in the normal category permission like Internet permission, not in dangerous category permission.

You don't have to ask for push notification permissions.

While Contacts/Locations are the dangerous permissions because you are accessing user data. So it is always needed to ask the user to allow it.

https://developer.android.com/guide/topics/security/permissions.html

Upvotes: 63

Rax
Rax

Reputation: 1567

Here's the answer to new update: In API 33 we need runtime permission for push notification: Full documentation is available here but you can simply use like below :

in app level:

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

you can trigger the prompt using this:

pushNotificationPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)

handle notification result:

private val pushNotificationPermissionLauncher = registerForActivityResult(RequestPermission()) { granted ->
            viewModel.inputs.onTurnOnNotificationsClicked(granted)
        }

Upvotes: 50

Ercan Akk&#246;k
Ercan Akk&#246;k

Reputation: 546

If your app targets Android 13 (Tiramisu) or higher, you must declare the POST_NOTIFICATIONS permission as follows:

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

For more details, see the Notification runtime permission page in the Android Developers documentation.

Upvotes: 17

Fakhriddin Abdullaev
Fakhriddin Abdullaev

Reputation: 4910

Try this:

In your Activity class, add the below code:

private static final int NOTIFICATION_PERMISSION_CODE = 123;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity);

    requestNotificationPermission();

    // Some code
}

 private void requestNotificationPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NOTIFICATION_POLICY) == PackageManager.PERMISSION_GRANTED)
        return;

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NOTIFICATION_POLICY)) {

    }

    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_NOTIFICATION_POLICY}, NOTIFICATION_PERMISSION_CODE );
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    // Checking the request code of our request
    if (requestCode == NOTIFICATION_PERMISSION_CODE ) {

        // If permission is granted
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Displaying a toast
            Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
        } else {
            // Displaying another toast if permission is not granted
            Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
        }
    }
}

Upvotes: -4

Related Questions