I am trying to implement SplashScreenActivity, which will request all necessary permissions and then redirect to the MainActivity:
public class SplashScreenActivity extends Activity {
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.splash_screen);
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
((TextView) findViewById(R.id.versionView)).setText(info.versionName);
} catch (Exception e) {
throw new IllegalStateException(e);
}
if (ActivityCompat.checkSelfPermission(this, CAMERA) != PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{READ_PHONE_STATE, CAMERA}, 200);
} else {
onPermissionsReady();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 200) {
onPermissionsReady();
}
}
private void onPermissionsReady() {
new Fork() {
#Override public void run() {
ApplicationContext.getInstance(SplashScreenActivity.this);
startActivity(new Intent(SplashScreenActivity.this, MainActivity.class));
}
};
}
}
I have two issues with it:
The splash screen design does not show before the Permission request dialog and the screen stays from the android background with application icons.
When you agree with the permissions, the onRequestPermissionsResult is NEVER called and the application ends.
EDIT: I created a sample application here: https://github.com/knyttl/TestApp – it demonstrates both two issues.
EDIT2: This is what happens when i agree/disagree with the permissions requests - the application just ends: https://www.youtube.com/watch?v=lhvhXcEJxLw&feature=youtu.be
You should extend from AppCompatActivity.
Try to change the line:
if (ActivityCompat.checkSelfPermission(this, CAMERA) != PERMISSION_GRANTED
to
`if (ActivityCompat.checkSelfPermission(this, Manifest.Permission.CAMERA) != PERMISSION_GRANTED`
Move the code for checking permission to onResume. Or leave it in onCreate but delay it, for example with Handler
I found out the problem: the activity has noHistory=true, which leads to killing the application as described here:
Requesting Android M permissions from Activity with noHistory="true" and/or showOnLockScreen="true"
Related
Hello I had simple application where I am using the camera, so the user must grant permission for the camera.
So far my app had only Activity, but now I want to use Fragments.
I got to fragments one is called FragmentScanCode (here I wanna use the camera ).
This is also the first fragment so I want to grant permission at the start of app.
There is my code from MainActivity, it works fine.
final int RequestCameraPermissionID = 1001;
onRequestPermissionsResult:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case RequestCameraPermissionID: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
RequestCameraPermissionID);
//return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
}
}
I can't use this in my Fragment because ActivityCompat.
Is any possible solution to grant permission on fragment?
This is what I tried based on developer.google.com doc and it works
This is working code for me.
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode){
case RequestCameraPermissionID: {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(getActivity().checkSelfPermission(Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.CAMERA},
RequestCameraPermissionID);
//cameraSource.start(cameraView.getHolder());
return;
}
}
captureCode();
}
break;
}
}
and also in my function captureCode()
try {
if (getActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.CAMERA},
RequestCameraPermissionID);
return;
}
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
This behavior seems to be present in the v4 Fragment support class requestPermissions in Fragment. The Activity/FragmentCompat implementations exist for people who wish to use the native classes with the extended functionality on API levels between 11 and 23. check this out
I'm searching to do a scan of available wifi networks but the method getScanResults() returns null list.
I included all permissions needed :
android.permission.ACCESS_COARSE_LOCATION
android.permission.CHANGE_WIFI_STATE
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_WIFI_STATE
The main activity class is :
public class Home extends Activity {`
Context context;
WifiManager wifiManager = null;
WiFiReceiver wifiReceiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
context = this;
wifiManager = (WifiManager)
context.getSystemService(Context.WIFI_SERVICE);
wifiReceiver = new WiFiReceiver(wifiManager);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiReceiver, intentFilter);
wifiManager.startScan();
List<ScanResult> results = wifiReceiver.results;
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(wifiReceiver);
}
}
The Broadcast Receiver is :
public class WiFiReceiver extends BroadcastReceiver {`
public List<ScanResult> results;
private WifiManager wifiManager;
public WiFiReceiver(WifiManager wifiManager) {
this.wifiManager = wifiManager;
}
#Override
public void onReceive(Context context, Intent intent) {
boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
if (success) {
results = wifiManager.getScanResults();
Log.e("wiFi Manager", "Done");
} else {
Log.e("wiFi Manager", "Scan failure");
}
}
}
The issue is that your are assuming that startScan() will produce a result immediately but it actually only does what is says, starting the scan. Your are accessing then results variable before onReceive in your WiFiReceiver has been triggered which is why it will always be null (your logging should confirm that).
What you need to to is use a callback to get the results when they're ready like the code here does. Notice how the onReceive method calls scanSuccess() and the results are only accessed in scanSuccess() and not immediately after calling startScan().
Also notice how they are checking if starting the scan was actually successful by checking the Boolean startScan() returns
From API level 23 (Android 6.0 Marshmallow) we need to ask Run-time permission from the user-end. Specifically ACCESS_FINE_LOCATION. You need to check whether the permission is granted before wifiManager.startScan(), and if permission is not granted, you need to call requestPermissions().
here is an example:
public void startScanningWifi(){if ( Build.VERSION.SDK_INT >= 23){
if (ActivityCompat.checkSelfPermission(context, Manifest.
permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED ){
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_ASK_PERMISSIONS);
Log.i(TAG, "User location NOT ENABLED, waiting for permission");
}else{
//Start scanning for wifi
}}
You will also need to include this method in the activity
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//start scanning
wifiManager.startScan();
} else {
// Permission for location Denied
Toast.makeText( this,"Well cant help you then!" ,
Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Dont forget to declare this in your activity as well
private final int REQUEST_CODE_ASK_PERMISSIONS = 1;
I have this app that will pick image to gallery and display it to the test using Imageview. My problem is it won't work on Android M. I can pick image but won't show on my test.They say i need to ask permission to access images on android M but don't know how. please help.
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.
Type 1- When your app requests permissions, the system presents a dialog box to the user. When the user responds, the system invokes your app's onRequestPermissionsResult() method, passing it the user response. Your app has to override that method to find out whether the permission was granted. The callback is passed the same request code you passed to requestPermissions().
private static final int PICK_FROM_GALLERY = 1;
ChoosePhoto.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v){
try {
if (ActivityCompat.checkSelfPermission(EditProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(EditProfileActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults)
{
switch (requestCode) {
case PICK_FROM_GALLERY:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
} else {
//do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
}
break;
}
}
Type 2- If you want to give runtime permission back to back in one place then you can follow below link
Android 6.0 multiple permissions
And in Manifest add permission for your requirements
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
Note- If Manifest.permission.READ_EXTERNAL_STORAGE produce error then please replace this with android.Manifest.permission.READ_EXTERNAL_STORAGE.
==> If you want to know more about runtime permission then please follow below link
https://developer.android.com/training/permissions/requesting.html
-----------------------------UPDATE 1--------------------------------
Runtime Permission Using EasyPermissions
EasyPermissions is a wrapper library to simplify basic system permissions logic when targeting Android M or higher.
Installation
Add dependency in App level gradle
dependencies {
// For developers using AndroidX in their applications
implementation 'pub.devrel:easypermissions:3.0.0'
// For developers using the Android Support Library
implementation 'pub.devrel:easypermissions:2.0.1'
}
Your Activity (or Fragment) override the onRequestPermissionsResult method:
#Override
public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
Request Permissions
private static final int LOCATION_REQUEST = 222;
Call this method
#AfterPermissionGranted(LOCATION_REQUEST)
private void checkLocationRequest() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if (EasyPermissions.hasPermissions(this, perms)) {
// Already have permission, do the thing
// ...
} else {
// Do not have permissions, request them now
EasyPermissions.requestPermissions(this,"Please grant permission",
LOCATION_REQUEST, perms);
}
}
Optionally, for a finer control, you can have your Activity / Fragment implement the PermissionCallbacks interface.
implements EasyPermissions.PermissionCallbacks
#Override
public void onPermissionsGranted(int requestCode, List<String> list) {
// Some permissions have been granted
// ...
}
#Override
public void onPermissionsDenied(int requestCode, List<String> list) {
// Some permissions have been denied
// ...
}
Link -> https://github.com/googlesamples/easypermissions
-----------------------------UPDATE 2 For KOTLIN--------------------------------
Runtime Permission Using florent37
Installation Add dependency in App level gradle
dependency
implementation 'com.github.florent37:runtime-permission-kotlin:1.1.2'
In Code
askPermission(
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) {
// camera or gallery or TODO
}.onDeclined { e ->
if (e.hasDenied()) {
AlertDialog.Builder(this)
.setMessage(getString(R.string.grant_permission))
.setPositiveButton(getString(R.string.yes)) { dialog, which ->
e.askAgain()
} //ask again
.setNegativeButton(getString(R.string.no)) { dialog, which ->
dialog.dismiss()
}
.show()
}
if (e.hasForeverDenied()) {
e.goToSettings()
}
}
Link-> https://github.com/florent37/RuntimePermission
public void pickFile() {
int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
CAMERA);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
getActivity(),
new String[]{CAMERA},
PERMISSION_CODE
);
return;
}
openCamera();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
if (requestCode == PERMISSION_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
}
}
}
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_CODE);
}
<uses-permission android:name="android.permission.CAMERA" />
I have a weird bug that is driving me crazy. I'm working on Android Marshmallow and I'm implementing the new permissions. When I click my Login button, I check to see if the user has gps permissions. If not, I request them. The way the code works is that after permissions are asked, an Async task is called to get some settings from a REST service, then on the onPostExecute of the Async task, it will fire an Intent.
When the user Allows permissions, everything works fine. If the user denies permissions, it will call the Async task and call the Intent, but it will not activate the Intent. It simply stays on the screen.
The Button Click
Button btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
int has_permission = 0;
if (Build.VERSION.SDK_INT >= 23)
{
has_permission = Check_Permission(Manifest.permission.ACCESS_FINE_LOCATION);
}
action = "login";
if(has_permission == 0)
{
Get_Location();
load_system_settings_async = new Load_System_Settings_Async();
load_system_settings_async.execute((Void) null);
}
}
});
Check Permission Code
protected int Check_Permission(final String permission)
{
int has_permission = checkSelfPermission(permission);
if (has_permission != PackageManager.PERMISSION_GRANTED)
{
if (!shouldShowRequestPermissionRationale(permission) && (request_times > 0))
{
String title="";
if(permission.equals(Manifest.permission.ACCESS_FINE_LOCATION))
{
title = "You need to allow GPS access";
}
else if(permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE))
{
title = "You need to allow storage access";
}
else if(permission.equals(Manifest.permission.CALL_PHONE))
{
title = "You need to allow access phone access";
}
Show_Alert_Dialog("Ok", title,
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//requestPermissions(new String[] {permission}, REQUEST_CODE_ASK_PERMISSIONS);
}
});
return has_permission;
}
requestPermissions(new String[] {permission}, REQUEST_CODE_ASK_PERMISSIONS);
request_times++;
return has_permission;
}
return has_permission;
}
Permission Request
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
if (requestCode == 123)
{
if(grantResults[0] == 0)
{
Get_Location();
}
load_system_settings_async = new Load_System_Settings_Async();
load_system_settings_async.execute((Void) null);
//request_times = 0;
}
else
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
it seems like the problem is when user denied the permission ,control fall in onRequestPermissionsResult where you are executing your asynch task even if the permission is not granted .check comment in following code
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions, #NonNull int[] grantResults)
{
if (requestCode == 123) // yes request code is the same go on
{
if(grantResults[0] == 0) //yes we get the approval
{
Get_Location();
}
// oh even if we didn't get the approval we still gonna execute the task
load_system_settings_async = new Load_System_Settings_Async();
load_system_settings_async.execute((Void) null);
//request_times = 0;
}
else //control only come here when request code will not match
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
you need to combine the if condition like this
if (requestCode == 123 && grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Ok, I figured it out .. When I was passing a custom Object with putExtra in the Intent, there was a property that was null, so when it was executing writeToParcel in the object, it was crashing. Unfortunately, Android kept executing with out crashing .. it just did nothing. I simply added a setter to the object and set the value to false. Issue had nothing to do with the Permission code. Four hours of life and sleep lost that I will not get back. Thanks all for who viewed.
Android Developer Documentation gives this example of requesting permissions at runtime:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
What is "MY_PERMISSIONS_REQUEST_READ_CONTACTS" in this example? It says it's an app-defined int constant, but does that mean I should make a Constants.java and declare a public static int? What should the value be?
In other examples I see people use 1 here, or 0 or 0xFFEEDDCC, but I can't find an explanation of what it is. Can someone explain to me what needs to go here and why? (In my case, I need to make sure the app has permission to access fine location)
The ActivityCompat documentation says "Application specific request code to match with a result reported to onRequestPermissionsResult"? This does not help me.
What is "MY_PERMISSIONS_REQUEST_READ_CONTACTS" in this example?
It is an int, to tie a particular requestPermissions() call to the corresponding onRequestPermissionsResult() callback.
Under the covers, requestPermissions() uses startActivityForResult(); this int serves the same role as it does in startActivityForResult().
does that mean I should make a Constants.java and declare a public static int?
I would just make it a private static final int in the activity. But, you can declare it wherever you want.
What should the value be?
I seem to recall that it needs to be below 0x8000000, but otherwise it can be whatever you want. The value that you use for each requestPermissions() call in an activity should get a distinct int, but the actual numbers do not matter.
If your activity has only one requestPermissions() call, then the int value really does not matter. But many apps will have several requestPermissions() calls in an activity. In that case, the developer may need to know, in onRequestPermissionsResult(), what request this is the result for.
Look just a little further down in the documentation under "Handle the permissions request response" and you will see its purpose.
A callback method called onRequestPermissionsResult gets sent back the same code as a parameter so you know which permission was being requested/granted:
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Since the constant is used by you only you can give it whatever value you like as a public static final int. Each permission being requested needs its own constant.
I went through all answers, but doesn't satisfied my exact needed answer, so here is an example that I wrote and perfectly works, even user clicks the Don't ask again checkbox.
Create a method that will be called when you want to ask for runtime permission like readContacts() or you can also have openCamera() as shown below:
private void readContacts() {
if (!askContactsPermission()) {
return;
} else {
queryContacts();
} }
Now we need to make askContactsPermission(), you can also name it as askCameraPermission() or whatever permission you are going to ask.
private boolean askContactsPermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(parentLayout, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
}).show();
} else if (contactPermissionNotGiven) {
openPermissionSettingDialog();
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
contactPermissionNotGiven = true;
}
return false;
}
Before writing this function make sure you have defined the below instance variable as shown:
private View parentLayout;
private boolean contactPermissionNotGiven;;
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
Now final step to override the onRequestPermissionsResult method as shown below:
/**
* Callback received when a permissions request has been completed.
*/
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
queryContacts();
}
}
}
Here we are done with the RunTime permissions, the addon is the openPermissionSettingDialog() which simply open the Setting screen if user have permanently disable the permission by clicking Don't ask again checkbox. below is the method:
private void openPermissionSettingDialog() {
String message = getString(R.string.message_permission_disabled);
AlertDialog alertDialog =
new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
.setMessage(message)
.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
dialog.cancel();
}
}).show();
alertDialog.setCanceledOnTouchOutside(true);
}
What we missed ?
1. Defining the used strings in strings.xml
<string name="permission_rationale">"Contacts permissions are needed to display Contacts."</string>
<string name="message_permission_disabled">You have disabled the permissions permanently,
To enable the permissions please go to Settings -> Permissions and enable the required Permissions,
pressing OK you will be navigated to Settings screen</string>
Initializing the parentLayout variable inside onCreate method
parentLayout = findViewById(R.id.content);
Defining the required permission in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
The queryContacts method, based on your need or the runtime permission you can call your method before which the permission was needed. in my case I simply use the loader to fetch the contact as shown below:
private void queryContacts() {
getLoaderManager().initLoader(0, null, this);}
This works great happy coding :)
public class SplashActivity extends RuntimePermissionsActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
SplashActivity.super.requestAppPermissions(new
String[]{android.Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, R.string.app_name
, 20);
}
#Override
public void onPermissionsGranted(int requestCode) {
try {
TelephonyManager tele = (TelephonyManager) getApplicationContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String imei =tele.getDeviceId()
} catch (Exception e) {
e.printStackTrace();
}
}
public abstract class RuntimePermissionsActivity extends AppCompatActivity {
private SparseIntArray mErrorString;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mErrorString = new SparseIntArray();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
for (int permission : grantResults) {
permissionCheck = permissionCheck + permission;
}
if ((grantResults.length > 0) && permissionCheck == PackageManager.PERMISSION_GRANTED) {
onPermissionsGranted(requestCode);
} else {
finish();
}
}
public void requestAppPermissions(final String[] requestedPermissions,
final int stringId, final int requestCode) {
mErrorString.put(requestCode, stringId);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
boolean shouldShowRequestPermissionRationale = false;
for (String permission : requestedPermissions) {
permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
shouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
}
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale) {
ActivityCompat.requestPermissions(RuntimePermissionsActivity.this, requestedPermissions, requestCode);
/*Snackbar.make(findViewById(android.R.id.content), stringId,
Snackbar.LENGTH_INDEFINITE).setAction("GRANT",
new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(RuntimePermissionsActivity.this, requestedPermissions, requestCode);
}
}).show();*/
} else {
ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
}
} else {
onPermissionsGranted(requestCode);
}
}
public abstract void onPermissionsGranted(int requestCode);
}