Android 6 permission Easy Permission library handle "Never check again" - android

Hi I'm Using Easy Permission library to handle android 6+ permission.
There is a method to call when "never ask again" is check
EasyPermissions.checkDeniedPermissionsNeverAskAgain
I dont know what parameter should we pass to the method
This is the method definition
public static boolean checkDeniedPermissionsNeverAskAgain(final Object object,
String rationale,
#StringRes int positiveButton,
#StringRes int negativeButton,
#Nullable DialogInterface.OnClickListener negativeButtonOnClickListener,
List<String> deniedPerms) {
boolean shouldShowRationale;
for (String perm : deniedPerms) {
shouldShowRationale = shouldShowRequestPermissionRationale(object, perm);
if (!shouldShowRationale) {
final Activity activity = getActivity(object);
if (null == activity) {
return true;
}
AlertDialog dialog = new AlertDialog.Builder(activity)
.setMessage(rationale)
.setPositiveButton(positiveButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
intent.setData(uri);
startAppSettingsScreen(object, intent);
}
})
.setNegativeButton(negativeButton, negativeButtonOnClickListener)
.create();
dialog.show();
return true;
}
}
return false;
}
But how to we pass the Stringres. Any help is much appreciate. Thanks

It just wants a resource value from your strings.xml file. So just pass something like R.string.okay and R.string.cancel. If you don't have a strings.xml file setup (you probably should) but could also use system defaults and pass android.R.string.ok and android.R.string.cancel to that method. There are several built in system strings like that. Look here if you're curious.

Related

Android Acitivity Life Cycle Handling error

Good Day, So I have this program where the user will scan a QR code and get the value of it in the SQLite database but before I get the value the dialog box pops-up messaging me that "there is no participant found". Below is my code:
This is my onStart override.
#Override
protected void onStart()
{
super.onStart();
getparticipantid = tvParticipantID.getText().toString();
etparticipantidvalue.setText(getparticipantid);
getParticipantIbeam();
}
This is my activity where it will load the data from the database once the user scans the QR code.
private void getParticipantIbeam()
{
SQLiteFunctionUlitity.GameIBeamParticipant memberInfo = SQLiteFunctionUlitity.getparticipantIbeam(getparticipantid, mDbHelper.getSqliteObjectWithReadable());
if (memberInfo != null)
{
tvParticipantName.setText(memberInfo.getParticipantName());
tvParticipantNation.setText(memberInfo.getParticipant_nationality());
tvParticipantCategory.setText(memberInfo.getCategory());
tvWave.setText(memberInfo.getWave_number());
tvCategory.setText(memberInfo.getCategory());
}
else
{
Context context = this;
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("No Participant found in the Game.");
builder1.setCancelable(true);
builder1.setPositiveButton("Scan Again", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(GameiBeamLineTracing.this, ScanGameIbeam.class);
startActivity(intent);
finish();
}
});
builder1.setNegativeButton("Close", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
onStop();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
As you can see I call the getParticipantIbeam activity in onStart method but when I call it, it reads the else statement rather than the if statement.
I know this is a simple if else statement and lifecycle but I am desperate to know the answer.
I have used the library for scanning QR code, its very simple it may help you.
QR Code implementation library for android, Click here (blikoon)
Definitely this library will solve your all QR Code related issue and dont forget to implement run time permissions like photo , gallery etc.

How to show popup window if users does not accepts all permission in Android Marshmallow?

I am following the example of Pokemon Go app to show a window message likes
You need to [Location, Camera,...] access to use this application. Please allow access in this application [Setting]. Click [Cancel] to exit from this application
When I click the Setting, the application will go to Setting window of this application and I can accept all Permissions.
The Setting window can access by using the code
public void gotoSetting(){
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + getApplicationContext().getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
}
There are my permisions which are stored in a String array
String[] PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA}
I used this code to check if all permission are checked, otherwise it returns false
public static boolean hasAllPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
However, I got an issue that event I did not check all permissions, but the application did not go to Setting again. In additions, I can show an window message to notify if the user did not check all permission. Finally, This is my code
private AlertDialog buildNotificationServiceAlertDialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Pemissions Setting");
alertDialogBuilder.setMessage("You need to [Location, Camera,...] access to use this application. Please allow access in this application [Setting]. Click [Cancel] to exit from this application");
alertDialogBuilder.setPositiveButton("Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
gotoSetting();
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// If you choose to not enable the notification listener
// the app. will not work as expected
}
});
return(alertDialogBuilder.create());
}
In onCreate I have
private AlertDialog enableNotificationListenerAlertDialog;
if(!hasAllPermissions(this, PERMISSIONS)){
enableNotificationListenerAlertDialog = buildNotificationServiceAlertDialog();
enableNotificationListenerAlertDialog.show();
}
Update: Solved:. I was missing to call the hasAllPermissions in the onResume() function. Finally, my solution is
#Override
protected void onResume() {
super.onResume();
if(hasAllPermissions(this, PERMISSIONS)==false){
enableNotificationListenerAlertDialog = buildNotificationServiceAlertDialog();
enableNotificationListenerAlertDialog.show();
}
}
I read your question carefully and i notice one mistake in your first line of code.As your code start with "public voide gotoSetting()",The mistake is in the keyword spelling.By correcting, it can be written as "public void gotoSetting()".
I hope this will help you.

Use Custom Class to Grant Permission

I am new to android. I am trying to grant permissions from custom class. I have two interfaces and a singleton class, like this
public interface RequestPermissionsResultInterface
{
void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults);
}
public interface PermissionManagerInterface
{
void onPermissionGranted(String message, int requestCode);
void onPermissionDenied(String message, int requestCode);
}
public class PermissionManager
{
private Activity mActivity;
private static volatile PermissionManagerInterface mManagerInterface;
public static PermissionManager getInstance(Context context)
{
if (mPermissionManager == null)
{
synchronized (PermissionManager.class)
{
if (mPermissionManager == null)
{
mPermissionManager = new PermissionManager(context);
}
}
}
return mPermissionManager;
}
private boolean isReadStorageAllowed()
{
int result = ContextCompat.checkSelfPermission(this.mActivity, Manifest.permission.READ_EXTERNAL_STORAGE);
return ((result == PackageManager.PERMISSION_GRANTED));
}
public RequestPermissionsResultInterface askPermission(
Activity mActivity,
String permissionName,
final PermissionManagerInterface managerInterface,
final int requestCode)
{
boolean isReadExternalStorageAllowed = isReadStorageAllowed();
if(isReadExternalStorageAllowed == false)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, permissionName))
{
final AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setMessage("Please allow all permissions in App Settings for additional functionality.");
builder.setCancelable(false);
builder.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
managerInterface.onPermissionGranted("Permission Granted", requestCode);
}
});
builder.setNegativeButton("Deny", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
managerInterface.onPermissionDenied("Permission Denied", requestCode);
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}
else managerInterface.onPermissionGranted("Permission Already Granted", requestCode);
}
}
And here is how I use this class in MainActivity
PermissionManager permManager = PermissionManager.getInstance();
permManager.askPermission(
MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE,
mPermissionManagerInterface, // assume this exists
EXTERNAL_STORAGE_PERMISSION_CODE);
Again.... it is not persistent. If I give permission, then stop and restart the app again....this is asking me for permission again. What could be wrong?? Thanks
If you are determined to go the "custom" method, you still need to handle certain things.
shouldShowRequestPermissionRationale is only true if you have previously requested a permission and was denied it. You seem to be using it to display a dialog saying "please grant permissions" but not actually asking the system to show the permission request dialog.
The command to actually request permissions is ActivityCompat.requestPermissions. Can't see this in your code. The user cannot grant permission unless you actually ask for them.
onRequestPermissionsResult is where you should be calling your interface to say permission was granted.
Full instructions are in the documentation.
https://developer.android.com/training/permissions/requesting.html
From Android Documentation
Note: When your app calls requestPermissions(), the system shows a standard dialog box to the user. Your app cannot configure or alter that dialog box.
I was trying to grant permission through custom dialog which was never going to work. This was only part of the problem.
I was not requesting permission in custom dialog code section (which would have been bad because I end up showing 2 dialogs: standard + my custom dialog). So I remove my custom dialog and stick to the standard one.
Kudos goes to kuffs because s/he put me in the right direction.

Return Boolean value from Android AlertDialog function

In my app i have a function that checks the entered text from a displayed AlertDialog with an input text. If the text is equal to a string variable, return True, else return False, and catch this resulting value to continue conditional code.
But it seems its a little difficult to do this as i've read in other posts asking how to solve the same problem.
I've already done this:
private boolean checkAdministratorPassword() {
final enterPasswordResult[0] = false;
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Confirm action");
alert.setIcon(R.drawable.ic_launcher);
alert.setMessage("Enter administrator pass to continue");
final EditText input = new EditText(mContext);
input.setPadding(5, 0, 5, 0);
alert.setView(input);
alert.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String strPass = input.getEditableText().toString();
if (strPass.length() == 0) {
dialog.cancel();
}
if (strPass.equalsIgnoreCase(Constantes.ADMIN_PASS)) {
enterPasswordResult[0] = true;
dialog.cancel();
} else {
Toast.makeText(mContext, "Invalid pass..!!", Toast.LENGTH_LONG).show();
dialog.cancel();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
return enterPasswordResult[0];
}
And i call the function this way:
If ( checkAdministratorPassword() == True ){
//true conditions
}
But the problem is that the check function doesnt wait for the result to continue with the code, it just continue by itself and i dont get the appropiate behavior.
The issue is you're trying to handle an async event in the logcal flow of your program. You can do this if you make the Dialog it's own class and use an Interface to callback to your host activity. Check out the documentation on DialogFragment.
public interface PasswordCheckListener{
public void valid(boolean check);
}
private static class PasswordDialog extends DialogFragment {
private PasswordCheckListener listener;
public static PaswordDialog newInstance(PasswordCheckListener listener){
this.listener = listener;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Put your dialog creation code here
}
private checkAdminPassword(){
//Whatever your check passowrd code is
listener.valid(result);
}
}
I realize I didn't implement all the code for you but that's the general idea. By using an interface you can call back to your host Activity or Fragment when the user enters the password and presses submit. You can then handle the event as it happens, rather than having to deal with it in your program flow.
Thank you all for your answers!! i've found the right way to achieve this problem by creating an Activity whith theme "Theme.Dialog", an input text and two buttons (Accept, Cancel), i start this activity for result asking the user to enter the administrator pass to continue, checking the string and then returning again to onActivityResult() from previous activity with the correct information to proceed.

Show Alert Dialog from Activity after activity returned result from a Fragment

The title might not be very clear, its kind of hard to explain in a short title. But here is the problem.
I have an activity, MainActivity which then shows an activity at start to show FragmentA. In MainActivity there is a menu that is shown which is accessible via FragmentA. From the menu in FragmentA the user clicks on Generate Password which then calls another activity called GeneratePassword called using startActivityForResult. When the user presses the submit button the user is then sent back to FragmentA and the function onActivityResult within the MainActivity. Within this function, I then make use of a common class which allows me to show an AlertDialog with Yes and No Buttons. OnActivityResult works fine if I take out the common.showYesNoDialog() if statement, but when this is being used I get an exception
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Below is the code that starts the GeneratePassword Activity
Intent generatePasswrodIntent = new Intent(mMainActivity, GeneratePassword.class);
startActivityForResult(generatePasswrodIntent, AddNewLogin.GENERATE_PASSWORD);
return(true);
Below is the code that sets the result from the GeneratePassword activity
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("password", generatePassword.generatePassword());
intent.putExtras(bundle);
setResult(AddNewLogin.GENERATE_PASSWORD, intent);
finish();
Below is the code from the onActivityResult that shows the alert dialog
Bundle bundle = data.getExtras();
String password = bundle.getString("password");
Log.d("PASSWORD", password);
if (common.showYesNoDialog("Your Generated Password Is:\n " + password + "\nDo you want to copy this to the clipboard?", false))
{
ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(password);
}
Below is the YesNoDialog function, but I know this works fine as I have used it in several places within my app without problem.
final Handler handler = new Handler()
{
#Override
public void handleMessage(Message mesg)
{
throw new RuntimeException();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(isCancelable);
builder.setMessage(message)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialogResult = true;
handler.sendMessage(handler.obtainMessage());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialogResult = false;
handler.sendMessage(handler.obtainMessage());
}
});
AlertDialog alert = builder.create();
alert.show();
try
{
Looper.loop();
}
catch (RuntimeException ex)
{
Log.d("Dialog Error", ex.toString());
}
return dialogResult;
And below is how I am initialising the common class
Common common = new Common(getApplicationContext());
Instead of getApplicationContext, I've tried using this but doesn't make any difference.
I just don't understand what is happening here.
Thanks for any help you can provide
The problem is in your showYesNoDialog(). What does the boolean parameter for your showYesNoDialog() method do?

Categories

Resources