open failed: EACCES (Permission denied) in marshmallow while upload image to server - android

Im working on the project which i want to send image to server. When i send image to server all versions except marshmallow works fine.
I got the permission while pick the image from gallery. Is there is any I any special permission to send image ?
private static int PICK_IMAGE_REQUEST = 1;
if (Build.VERSION.SDK_INT <= 19) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_IMAGE_REQUEST);
} else if (Build.VERSION.SDK_INT > 19) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_IMAGE_REQUEST);
}

AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
IN Activity
private static final int REQUEST_STORAGE = 112;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST_STORAGE );
} else {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_IMAGE_REQUEST);
}
} else {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_IMAGE_REQUEST);
}
/*get Permissions Result*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_IMAGE_REQUEST);
} else {
Toast.makeText(mContext, "The app was not allowed to write to your storage.", 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;
}

You need to ask runtime permissions for user. Check this link https://developer.android.com/training/permissions/requesting.html

There is one more permission of Internet that might be missing to give.
"<uses-permission android:name="android.permission.INTERNET" />"
Also do go to settings and check if the permission has been granted as in marshmallow the permission is needed to be given at runtime..
Check below link....
https://developer.android.com/training/permissions/requesting.html
Hope your problem gets resolved with this...

Related

Why Video not saving given path using ffmpeg in android?

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();
}
}

Android : save/open picture taken from camera intent

I have a camera intent that takes a picture that I want to save anywhere as a temp file :
File photo = new File(Environment.getExternalStorageDirectory(), "myTempPicture.jpg");
imageUri = Uri.fromFile(photo);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,0);
(Maybe the choice of Storage is not the right one)
Then after the picture was taken, I need to open it to process it :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
process(bitmap, false);
}catch(Exception e){
Log.d("exception : ", e.toString());
}
}
But I get the following Exception : java.io.FileNotFoundException: /storage/emulated/0/savedImage.jpg (Permission denied).
What went wrong ?
My Manifest file contains :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
with android 6.0+ or SDK 23 and above you have to ask runtime permission in your activity
here an example how you can do that, here 1 is your request code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
}
and then you should check if user granted permission
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
}
for more detailed guide about runtime request have a look here at official documentation

Missing Permissions required be intent Intent.ACTION_CALL:android.permission.CALL_PHONE

I'm trying to Call a number programmatically with the code provided below:
if(ActivityCompat.checkSelfPermission(MainActivity.this,Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CALL_PHONE},CALL);
}
else
{
String number="56789855";
Intent intent4=new Intent(Intent.ACTION_CALL);
intent4.setData(Uri.parse("tel:"+number));
startActivity(intent4);
}
I've set the permission in Android Manifest File as well:
<uses-permission android:name="android.permission.CALL_PHONE"> </uses-permission>
Android Studio throws an error called:
Missing Permissions required be intent Intent.ACTION_CALL:android.permission.CALL_PHONE
I can't seem to find why this error occurs.Any help will be appreciated.
Try this,
Required android.Manifest.permission.CALL_PHONE instead of Manifest.permission.CALL_PHONE
private Context mContext=YourActivity.this;
private static final int REQUEST = 112;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.CALL_PHONE};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
} else {
makeCall();
}
} else {
makeCall();
}
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) {
makeCall();
} else {
Toast.makeText(mContext, "The app was not allowed to call.", 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.CALL_PHONE" />
call function:
public void makeCall()
{
String number="56789855";
Intent intent4=new Intent(Intent.ACTION_CALL);
intent4.setData(Uri.parse("tel:"+number));
startActivity(intent4);
}

java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider in Android while taking picture from gallery

I'm trying to select the image from gallery , but my application is getting exception of 'Something went wrong' message . I thought i set up the android WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permission correctly, but i keep getting errors What should i do to have it working?
Here is my Log cat error
06-07 12:07:27.567 1692-1711/? E/DatabaseUtils﹕ Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/359 from pid=2818, uid=10057 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:605)
at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:480)
at android.content.ContentProvider$Transport.query(ContentProvider.java:211)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
at android.os.Binder.execTransact(Binder.java:453)
Here is my Activity code
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
}
Here is my Menifest.xml file code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tazeen.image_fromgallery" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
For checking manual permissions for API level 23 and above i use this code.
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
public boolean checkPermissionREAD_EXTERNAL_STORAGE(
final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
(Activity) context,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialog("External storage", context,
Manifest.permission.READ_EXTERNAL_STORAGE);
} else {
ActivityCompat
.requestPermissions(
(Activity) context,
new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
showDialog()
public void showDialog(final String msg, final Context context,
final String permission) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage(msg + " permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[] { permission },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
in your activity check like this.
if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
// do your stuff..
}
And don't forget to add onRequestPermissionsResult.
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// do your stuff
} else {
Toast.makeText(Login.this, "GET_ACCOUNTS Denied",
Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
Happy Coding..
You have two solutions for your problem. The quick one is to lower targetApi to 22 (build.gradle file). Second is to use the new runtimePermission model: Since your target api is 23 you should add the permissions on runtime too.
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.READ_EXTERNAL_STORAGE) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant
return;
}
Sniplet found here: https://developer.android.com/training/permissions/requesting.html
You need to set permissions explicitly to all packages match your intent.
you can use this utility to do that :
List<ResolveInfo> resInfoList = getContext().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
getContext().grantUriPermission(packageName, imageFileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
There is an easy way, set an action to your "galleryIntent" so the OS will not panick (I test this on Andorid Emulator API 23 and it works):
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
Also, don't forget to set a type too:
galleryIntent.setType("image/*");
Change:
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
To:Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
=> done !

Application crashed after selecting contact from Contacts in android 6.0

From my activity when i call Contacts to get a contact number the application crashed. Application is running ok on other devices but when i'm try to run it in android 6.0, it crashed. i've no idea what i'm doing wrong.
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
After getting the the data in onActivityResult method.
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = this.getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phoneNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
Log.d(TAG, "name : "+name+" , Phone Number : "+ phoneNumber);
}
}
break;
}
}
can Anyone help me ?
All of the answers here are wrong. You shouldn't need READ_CONTACT permission at all to retrieve single contact using ACTION_PICK intent. You should be granted this permission temporary to be able to retrieve contact specific data. However there are some devices that don't implement this API in a good way. Myself I have found Sony Xperia Z3, but I heard about HTC devices also had this problem.
To have the user select a contact and provide your app access to all the contact information, use the ACTION_PICK action and specify the MIME type to Contacts.CONTENT_TYPE.
The result Intent delivered to your onActivityResult() callback contains the content: URI pointing to the selected contact. The response grants your app temporary permissions to read that contact using the Contacts Provider API even if your app does not include the READ_CONTACTS permission.
Source: https://developer.android.com/guide/components/intents-common.html#Contacts
[UPDATE]
After upgrading Sony Xperia Z3 system image to version 23.5.A.1.291 bug does not occur anymore.
From android 6.0 (Mashmello) , android has introduced Run Time Permissions for users to grand permission to apps while the app is running, not when they install the app. So, Your calling should be like this ->
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
/*If Android M*/
if (ContextCompat.checkSelfPermission(SendMoneyByDetailsActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
/*If Android M and Not permission granted */
ActivityCompat.requestPermissions(SendMoneyByDetailsActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
/*If Android M and permission granted */
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
} else {
/*IF not Android M*/
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
And when user grant the permission then you can call the intent to pick contact list ->
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 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
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
} else {
// permission denied
}
return;
}
}
}
And don't forgot to add permission in your manifest file.
<uses-permission android:name="android.permission.READ_CONTACTS" />
It not your manifest problem its problem with android 6.0 it requires Runtime Permissions...
after adding this in manifest
<uses-permission android:name="android.permission.READ_CONTACTS" />
Just change your code to this In your code..
public class MainActivity extends Activity {
public static final int REQUIRED_PERMISSIONS = 001;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//give here permissions what ever you want...
// if you are using one add only one... not all..
if ((CheckPermission(this, Manifest.permission.READ_CONTACTS))&&
(CheckPermission(this, Manifest.permission.READ_PHONE_STATE))&&
(CheckPermission(this, Manifest.permission.INTERNET))&&
(CheckPermission(this, Manifest.permission.ACCESS_NETWORK_STATE))&&
(CheckPermission(this, Manifest.permission.ACCESS_WIFI_STATE)))
{
PermHandling();
}
//now reqest runtime permissions..
else {
RequestPermission(MainActivity.this, Manifest.permission.READ_CONTACTS, REQUIRED_PERMISSIONS);
RequestPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE, REQUIRED_PERMISSIONS );
RequestPermission(MainActivity.this, Manifest.permission.INTERNET, REQUIRED_PERMISSIONS );
RequestPermission(MainActivity.this, Manifest.permission.ACCESS_NETWORK_STATE, REQUIRED_PERMISSIONS );
RequestPermission(MainActivity.this, Manifest.permission.ACCESS_WIFI_STATE, REQUIRED_PERMISSIONS );
}
}
private void PermHandling() {
//Your app internal parts....
//Here your stuff works...
}
//private void NewPermHandling(){
//}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUIRED_PERMISSIONS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
PermHandling();
} else {
//Toast.makeText(this, "Please Grant Permissions other wise app will close.!", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
public void RequestPermission(Activity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity,
Permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Permission)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Permission},
Code);
}
}
}
public boolean CheckPermission(Context context, String Permission) {
if (ContextCompat.checkSelfPermission(context,
Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
}
I also faced same problem my applications worked on till 5.1 but 6.0+ due to Runtime permissions We need to add them.. and accept those permissions at runtime
I think this is permission issue
add bellow permission inside manifest file
<uses-permission android:name="android.permission.READ_CONTACTS" />
accept permissions in marshmallows
https://developer.android.com/training/permissions/requesting.html
actual implementation
add bellow code inside Main Activity
call checkAndAddPermission() method inside onCreate() method
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 1244;
private void checkAndAddPermission() {
List<String> permissionsNeeded = new ArrayList<>();
final List<String> permissionsList = new ArrayList<>();
if (!addPermission(permissionsList, android.Manifest.permission.READ_CONTACTS))
permissionsNeeded.add("ReadContacts");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
ActivityCompat.requestPermissions(MainActivity.this, permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
} else {
ActivityCompat.requestPermissions(MainActivity.this, permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
}
#TargetApi(Build.VERSION_CODES.M)
private boolean addPermission(List<String> permissionsList, String permission) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<>();
// Initial
perms.put(android.Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}

Categories

Resources