Alexei
Alexei

Reputation: 15664

How handle when snackbar return result?

Android studio 3.6

In my activity I has snackbar:

 val snackbar = Snackbar.make(
                    findViewById(android.R.id.content),
                    getString(R.string.user_denied_permission_permanently_info),
                    Snackbar.LENGTH_LONG
                ).setAction(getString(R.string.setttings)) {
                    startActivity(
                        Intent(
                            android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                            Uri.parse("package:" + BuildConfig.APPLICATION_ID)
                        )
                    )
                }
                val snackbarView = snackbar.view
                val textView =
                    snackbarView.findViewById<View>(com.google.android.material.R.id.snackbar_text) as TextView
                textView.maxLines = 5  //Or as much as you need
                snackbar.show()

As you can see after click on "Settings" on snackbar then show settings of my application. I enter on "Permissions" on my app, change it and by back button (press 2 times) I return to my activity. As result in my activity call onResume() But I need to get result of change permission. If permission was changed I need to to some specific work.

How I can understand that permission was changed?

Upvotes: 0

Views: 310

Answers (1)

You need to use onRequestPermissionsResult method to get the state of permission (granted or denied) :

in your question you didn't mention any permission so I will go with WRITE_EXTERNAL_STORAGE for example :

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
        } else
            Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
    }

onRequestPermissionsResult method lets you know if the user granted or denied the permission

onResume method :

@Override
    protected void onResume() {
        super.onResume();
        if(!checkPermission())
            Toast.makeText(this, "No action", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
    }

check permission is granted or not so you can show the Snackbar or not :

 private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED;
    }

Upvotes: 1

Related Questions