I'm using that library: https://github.com/AlmogBaku/IntlPhoneInput to get user phone number.
I want to detect and select automatically the local country of the user.
Reading that: https://github.com/AlmogBaku/IntlPhoneInput#public-methods,
I added that: android.permission.READ_PHONE_STATE in my AndroidManifest.xml but can't detect and select automatically the local country of the user.
Any help ?
If you are using API-level 23+, then android.permission.READ_PHONE_STATE in manifest won't be sufficient and you need to request it programmatically, and to do so
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_READ_STATE = 21;
private IntlPhoneInput mPhoneInputView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// We do not have this permission. Let's ask the user by showingg a dialog
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_READ_STATE);
}
mPhoneInputView = findViewById(R.id.my_phone_input);
}
// Called when the user decides the dialog permission
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_READ_STATE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted!
mPhoneInputView.setDefault();
} else {
// permission denied
}
}
}
...
}
Related
In our android webview app, We ask for read_contacts, location, camera, audio permissions at a time on initialization of app. What happens is that simultaneously the webview url is also loaded. This causes some crucial data like location not to be passed to webview in the first load.
What we expect from the app is to load the webview url immediately after user allows, grants permissions for the above only and not before that. We tried using onRequestPermissionsResult for achieving this, but unable to do so. The code we have tried is as given hereunder
if (!check_permission(4) || !check_permission(3)) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_PHONE_NUMBERS,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.RECORD_AUDIO,Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},
contact_perm);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults){
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
get_location();
asw_view.loadUrl(url);
}
}
}
Any help would be appreciated.
You're checking only for 0th element, i.e., grantResults[0] == PackageManager.PERMISSION_GRANTED in onRequestPermissionsResult(...).
You need to check like this:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 1) {
// Use this method to check if all the permissions are GRANTED.
if (areAllPermissionsGranted(grantResults)) {
get_location();
asw_view.loadUrl(url);
} else {
/*
* NOTE:
* -----
* Add a Log here to check if all the permissions are granted.
* If this block doesn't executes, it means all the permissions are granted,
* something else is wrong inside your 'if' block and you need to debug that block.
* */
}
}
}
// Method to check if all the results are GRANTED.
private Boolean areAllPermissionsGranted(int[] grantResults) {
boolean isGranted = false;
if (grantResults.length > 0) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_GRANTED) {
isGranted = true;
} else {
// if a single permission is NOT_GRANTED, return from the method.
return false;
}
}
}
return isGranted;
}
Use this library
gradle:
implementation 'com.nabinbhandari.android:permissions:3.8'
then:
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION}; //add your requested permissions to this array
String rationale = "Please provide location permission so that you can ...";
Permissions.Options options = new Permissions.Options()
.setRationaleDialogTitle("Info")
.setSettingsDialogTitle("Warning");
Permissions.check(this/*context*/, permissions, rationale, options, new
PermissionHandler() {
#Override
public void onGranted() {
// do your task here
}
#Override
public void onDenied(Context context, ArrayList<String> deniedPermissions) {
// permission denied, block the feature.
}
});
I want to use ffmpeg to save video as given path in android.
I am using this command for saving the video but it doesn't work.
Where am I mistaken?
String[] command_try = new String[13];
command_try[0] = "-i";
command_try[1] = "/sdcard/Videos/Videos/f2a804f062384d4da3995d3bdce15610.mp4";
command_try[2] = "-i";
command_try[3] = "/sdcard/Videos/Videos/vidlogogif.gif";
command_try[4] = "-filter_complex";
command_try[5] = "overlay=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2";
command_try[6] = "-pix_fmt";
command_try[7] = "yuv420p";
command_try[8] = "-c:a";
command_try[9] = "copy";
command_try[10] = "-preset";
command_try[11] = "ultrafast";
command_try[12] = "/sdcard/Videos/Videos/video11.mp4";
First step is to add permissions to manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Then add "Permission asking" code to java file
call hasPermission(); from your activity's onCreate() and here's your method :
private void hasPermission() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
final String[] s = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
PermissionsDialog(s);
} else {
// do something when you got permission
}
} else {
// do something when you got permission
}
}
Android app requires user permission on devices with api >= 23
This will ask for permission if your device's api version is >= 23, if it is below 23 or permission is already granted then next task will be performed.
if user deny permission then PermissionsDialog(s); will be called for asking permission.
private void PermissionsDialog(final String[] s) {
ActivityCompat.requestPermissions(MainActivity.this, s, Helper.REQUEST_PERMISSION);
}
Then if user allow or deny permission it comes in this method :
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == Helper.REQUEST_PERMISSION) {
if (grantResults.length > 0) {
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permissions[0])) {
startActivityForResult(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + BuildConfig.APPLICATION_ID)), Helper.SETTINGS_CODE);
} else {
hasPermission();
}
} else {
// do something when you got permission
}
}
}
}
}
This method checks if permission is granted or not and it continues to ask for permission until you allow and if you deny for permission with don't ask again then we have to navigate user to App Setting Screen for allowing permission manually.
Now,when user comes from setting screen onActivityResult(...) of activity will be called, here call hasPermission(); for recheck if user granted permission from setting screen or not which is as below :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Helper.SETTINGS_CODE) {
hasPermission();
}
}
I have a method in the beginning of the activity to ask the permissions, but in the code when I want to get location coordinates, appear a error about permissions request.
This is for Android SDK 28.0.2. I've tried adding the permissions requeste in all lines that I request for coordinates.
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
checkPermissions();
...
}
public void myPosition() {
//One of lines where appear the error
Location loca = locaMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (loca != null) {
mapCamera(loca.getLatitude(), loca.getLongitude());
pass = true;
savePosition(loca);
}
}
private void checkPermissions() {
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (!(grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
//Show error
finish();
}
}
}
}
I want do this permissions check only once. But now I see the following error:
Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException
I am working with media recorder in my application.When I am asking for permission for Record audio in marshmallow and above versions it is returning me permission granted everytime. Here is my code.
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
// Requesting permission to RECORD_AUDIO
private boolean permissionToRecordAccepted = false;
private String[] permissions = {Manifest.permission.RECORD_AUDIO};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Defined SoundLevelView in main.xml file
setContentView(R.layout.activity_noice_meter);
//check for permission
ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted) {
finish();
} else {
//Task to be done when permission is granted
//init();
}
}
Use below code inside onCreate. Here you are not checking whether permission is granted or not.
// 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.RECORD_AUDIO)) {
// Show an explanation 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(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);
}
}
Try this,
private Context mContext=YourActivity.this;
private static final int REQUEST = 112;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.RECORD_AUDIO};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
} else {
//do here
}
} else {
//do here
}
get Permissions Result
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do here
} else {
Toast.makeText(mContext, "The app was not allowed to record audio", Toast.LENGTH_LONG).show();
}
}
}
}
check permissions for marshmallow
private static boolean hasPermissions(Context context, String... permissions) {
if (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;
}
Manifest
<uses-permission android:name="android.permission.RECORD_AUDIO" />
New Runtime Permission will work like described only when we set the application's targetSdkVersion to 23. If the application's targetSdkVersion is set to less than 23. It will be assumed that application is not tested with new permission system yet and will switch to the same old behavior: user has to accept every single permission at install time and they will be all granted once installed !
Long story short : Please check yopur target sdkversion first and implement the code as shown by #jitesh mohite
i am adding certain permissions to my app to allow access to camera for example and everything is working fine. but when i minimize the app and disable the permission then open the app, the app crashes without asking me to re-enable the permission(until i close the app and then open it). how can i fix this error so that the app dont crash and ask again for permission or safe restart to ask for permissions.
here is my code
in the main activity:
onCreate:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
GlobalVariables.MY_PERMISSIONS_REQUEST_CAMERA);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode)
{
case GlobalVariables.MY_PERMISSIONS_REQUEST_CAMERA:
{
if (grantResults.length <= 0
|| grantResults[0] != PackageManager.PERMISSION_GRANTED) {
globalVariables.ShowOKAlert("Error","Please Accept All Requested Permissions or the app wont function properly",this,false);
}
return;
}
}
}
the activity implements ActivityCompat.OnRequestPermissionsResultCallback
step 1:
String[] permissions = new String[]{
Manifest.permission.INTERNET,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
Step 2:-
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p : permissions) {
result = ContextCompat.checkSelfPermission(this, p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 100);
return false;
}
return true;
}
Step 3:
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == 100) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// do something
}
return;
}
}
You are checking that permission in onCreate. When you minimize and maximize the app again that method is not called.
Maybe you should check that permission in the extact point where you need it, or at least in onResume which surely is called again when you re-open your app.
Calling it in onResume ensure the app continues to work also if the user disables the permission in another window with the screen splitted (Android N feature).
The easy way to achieve this to use direct static method of ActivityCompat
public static void requestPermissions(final #NonNull Activity activity,
final #NonNull String[] permissions, final int requestCode)
Here you can see what parameters you have required for this
-- Activity Instance
-- String array of permissions
-- a user defined request code
Usage
Define global variables
//Run-time permissions for MarshMallow +
public final String[] PERMISSION_ALL = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
//validateRequestPermissionsRequestCode requires requestCode to be of 8 bits, i.e. range: 0-255.
public final int PERMISSION_REQUEST_CODE = 100;
Finally in your activity oncreate() method you can call static function mentioned above
public class MainActivity extends AppCompatActivity
{
//your code here
#Override
protected void onCreate(Bundle savedInstanceState)
{
//do other code work
super.onCreate(savedInstanceState);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M)
{
ActivityCompat.requestPermissions(this, PERMISSION_ALL, PERMISSION_REQUEST_CODE);
}
//do other code work
}
//your code here
}
And you are done....
For more Info Click here about Android Permissions At Run Time