Failed to create directory in Android (on MarshMallow and above) devices - android

I am trying to create a folder on my sdcard using the following code but it fails. This is my code written in onCreate():
File test = new File(Environment.getExternalStorageDirectory(),"my_directory");
if(!test.exists())
{
try
{
if (test.mkdir())
{
Log.d("xxx", "directory created");
}
else
{
Log.d("xxx", "directory creation failed");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Log.d("xxx","directory already present");
}
When I run the above code does not give any exception it just prints the
directory creation failed log.
I have also given the following permission,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I am using Xiaomi Redmi note 3 and Android version is 6.0.1.

Try this code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkPermission()) {
//do your work
} else {
requestPermission();
}
}
}
protected boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
protected void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do your work
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}

I know it just for API 21 (couse i wanted the same at my app, till now i do not know how to get on the sdcard)
you also need this in your manifest!!
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
Environment.getExternalStorageDirectory() declares the internal storage.
the exact path is: storage/emulated/0
you get it with:
Log.i(TAG, "path is:" + Environment.getExternalStorageDirectory().toString());

Related

Can't modify file in external storage in android

Please help me... I'm getting
java.io.FileNotFoundException : /storage/'my external storage'/Music/'file name' : open failed: EACCES (Permission denied)
when I'm modifying music's id3 tags which are located in my sd card with jaudiotagger.
I already wrote read/write permissions on manifest file, and I wrote requesting method, permission request result callback method, and a part that modify tags when button clicked like this.
private void requestExternalStoragePermissions() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted to write your External storage", Toast.LENGTH_SHORT).show();
start();
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1 : {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0&&grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
start();
}
else {
Toast.makeText(this, "Permission denied to access your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
savebutton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view){
try{
AudioFile f = AudioFileIO.read(file);
Tag tag = f.getTag();
tag.setField(FieldKey.TITLE,editText1.getText().toString());
tag.setField(FieldKey.ALBUM,editText2.getText().toString());
tag.setField(FieldKey.ARTIST,editText3.getText().toString());
tag.setField(FieldKey.ALBUM_ARTIST,editText4.getText().toString());
tag.setField(FieldKey.YEAR,editText5.getText().toString());
tag.setField(FieldKey.DISC_NO,editText6.getText().toString());
tag.setField(FieldKey.TRACK,editText7.getText().toString());
tag.setField(FieldKey.LYRICS,editText8.getText().toString());
f.commit();
Toast.makeText(getApplicationContext(), "Tag Saved", Toast.LENGTH_SHORT).show();
} catch(Exception e){
e.printStackTrace();
}
}
});
How can I fix this?
In Android 4.4 and higher, editing files on the sd card is not possible anymore. I had the same issue..
The only workaround is to copy the file to the internal storage, modify it and move it back.

Android camera runtime permission error?

I am trying to use Camera2 api in my app even though i am checking runtime camera permission using the following code.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraManager.openCamera(cameraId, stateCallBack, null);
} else {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA))
Toast.makeText(getApplicationContext(), "PLease allow the app to use camera app", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(CaptureImageActivity.this,new String[]{"android.manifest.permissin.CAMERA"}, CAMERA_REQUEST_RESULT);
} else {
cameraManager.openCamera(cameraId, stateCallBack, null);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permission, int[] grantResult) {
switch (requestCode) {
case CAMERA_REQUEST_RESULT:
if (grantResult[0] == PackageManager.PERMISSION_GRANTED) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//this method is created because of openCamera method below i don't understand why this method is created
return;
}
cameraManager.openCamera(cameraId, stateCallBack, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
if (grantResult[0] != PackageManager.PERMISSION_GRANTED)
Toast.makeText(getApplicationContext(), "camera is not granted", Toast.LENGTH_LONG).show();
break;
default:
super.onRequestPermissionsResult(requestCode, permission, grantResult);
break;
}
}
I have also permission included in the AndroidManifest.xml file.
<uses-permission android:name="android.permission.CAMERA" />
But when i run my app the permission dialog is not showing up but camera is not granted toast is showing up.
1) Why is the permission dialog not showing up?
2) Even there is no dialog showing up how is the camera is not granted toast showing up? I have searched a lot but nothing help!
Here is the working runtime permission for camera api
private static final int PERMISSIONS_REQUEST_CAPTURE_IMAGE = 1;
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// User may have declined earlier, ask Android if we should show him a reason
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
// show an explanation to the user
// Good practise: don't block thread after the user sees the explanation, try again to request the permission.
} else {
// request the permission.
// CALLBACK_NUMBER is a integer constants
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAPTURE_IMAGE);
// The callback method gets the result of the request.
}
} else {
}
#Override
public void onRequestPermissionsResult ( int requestCode, String[] permissions,
int[] grantResults){
switch (requestCode) {
case PERMISSIONS_REQUEST_CAPTURE_IMAGE: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
Log.d("", "permission granted success");
} else {
// permission denied
Log.d("", "permission denied");
}
return;
}
}
}

Android requestPermission Dialog not showing up

I am working with a Samsung Galaxy Tab S tablet and try to grant permission to write on the external storage at runtime.
However the dialog to request the permission does not show up. Instead in the code onRequestPermissionResult will be executed instantly with the a PERMISSION_DENIED result. I even tried granting the storage permission manually in the application settings on the device, but even then the result will be PERMISSION_DENIED (grantResults is -1).
My code looks like this:
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_STORAGE_PERMISSION = 225;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
process();
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_STORAGE_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_LONG).show();
process();
} else {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_LONG).show();
}
}
}
public void process() {
//...
}
}
When starting the application, it will instantly show the "Permission Denied"-Toast, without showing me any dialog before. That happens, even if i grant the Storage-permission manually in the app settings of the tablet.
My manifest-file also contains the permission at the right place (outside of the application tags) as suggested in similar threads.
I tried reinstalling the app and even reset the tablet already, but nothing seems to work.
instead of:
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
it works for fragments
You need to use this: As you are using AppCompatActivity
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
EDIT
As you have multiple project module: you need to add permission in both of those Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Do this thing
private boolean RequestPermissions() {
int camera = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.CAMERA);
int storage = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (camera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(CAMERA);
}
if (storage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(WRITE_EXTERNAL_STORAGE);
listPermissionsNeeded.add(READ_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(getActivity(), listPermissionsNeeded.toArray
(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}

I can't show Manifest.permission.CALL_PHONE in runtime permission

I'm implementing the runtime permissions in my app but I can't do that show the permission for CALL_PHONE. I need to show two permission, read_contact and call_phone. I can show perfectly read_contact but not call_phone permission.
I'm using the AVD emulator to test it.
Some help will be apreciate!
This is my code:
callPesmission.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
requestCallPhonePermission();
}
});
contactPesmission.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
requestContactsPermission();
}
});
private void requestContactsPermission() {
String locationPermission = Manifest.permission.READ_CONTACTS;
int hasPermission = ContextCompat.checkSelfPermission(getActivity(), locationPermission);
String[] permissions = new String[] { locationPermission };
if (hasPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, REQUEST_CONTACTS);
} else {
Toast.makeText(getActivity(), "We already have persmission", Toast.LENGTH_SHORT).show();
}
}
private void requestCallPhonePermission() {
String callPermission = Manifest.permission.CALL_PHONE;
int hasPermission = ContextCompat.checkSelfPermission(getActivity(), callPermission);
String[] permissions = new String[] { callPermission };
if (hasPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, REQUEST_CALL_PHONE);
} else {
Toast.makeText(getActivity(), "We already have persmission", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CONTACTS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "READ_CONTACTS GRANTED", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "READ_CONTACTS DENIED", Toast.LENGTH_SHORT).show();
}
break;
case REQUEST_CALL_PHONE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "CALL_PHONE GRANTED", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "CALL_PHONE DENIED", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
I forget to add the permission in the manifest.....
<uses-permission android:name="android.permission.CALL_PHONE" />
I see nothing wrong with your code right there,
Confirm if it actually is present in manifest.xml.
Dialog won't show if its not present in manifest and might throw security exception if we try to use the feature anyway
add this
private static final int PHONE_CALL_REQUEST=0;
and your button
if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.CALL_PHONE},PHONE_CALL_REQUEST);
}
else
{
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "+01723915447"));
startActivity(intent);
}
Step 1:
<uses-permission android:name="android.permission.CALL_PHONE" />
Step 2:
<permission
android:name="mypackage.permission.CALL_PHONE"
android:protectionLevel="signature" />
NB: mypackage in Step 2 is your root project package name e.g com.myapp hence the above in step 2 will become
<permission
android:name="com.myapp.permission.CALL_PHONE"
android:protectionLevel="signature" />
Last Step:
In your Java/Kotin function Manifest.permission.CALL_PHONE will be available
Use in Oreo,
android.Manifest.permission.CALL_PHONE
You forgot the android. part.

Android 6(M) permission issue (create directory not working)

I have this code for creating directory for saving pictures:
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myphoto");
if (!storageDir.mkdirs()) {
if (!storageDir.exists()){
Log.d("photo", "failed to create directory");
return null;
}
}
}
return storageDir;
storeDir returns "/storage/emulated/0/Pictures/myphoto/" below android 6 and on android 6 it returns null.
I have permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
buildToolVersion 23
targetSdkVersion 23
How to fix?
As #CommonsWare answered, there is run-time permission asking concept on Android M, so in new approach, permissions are not asked when installing the app but when trying to use specific feature of phone which requests permission, at run-time. User later can disable permission from phone settings->app->yourapp->permissions as well. So you have to check before doing something with that permission, and ask user:
int REQUEST_WRITE_EXTERNAL_STORAGE=1;
////...
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//RUNTIME PERMISSION Android M
if(PackageManager.PERMISSION_GRANTED==ActivityCompat.checkSelfPermission(context,Manifest.permission.WRITE_EXTERNAL_STORAGE)){
storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myPhoto");
}else{
requestPermission(context);
}
}
return storageDir;
////...
private static void requestPermission(final Context context){
if(ActivityCompat.shouldShowRequestPermissionRationale((Activity)context,Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// For example if the user has previously denied the permission.
new AlertDialog.Builder(context)
.setMessage(context.getResources().getString(R.string.permission_storage))
.setPositiveButton(R.string.tamam, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_EXTERNAL_STORAGE);
}
}).show();
}else {
// permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions((Activity)context,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_EXTERNAL_STORAGE);
}
}
///...
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case UtilityPhotoController.REQUEST_WRITE_EXTERNAL_STORAGE: {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context,
getResources().getString(R.string.permission_storage_success),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context,
getResources().getString(R.string.permission_storage_failure),
Toast.LENGTH_SHORT).show();
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
return;
}
}
}
You are running this on an Android 6.0+ environment and you have a targetSdkVersion of 23.
In that case, WRITE_EXTERNAL_STORAGE is part of the Android 6.0 runtime permission system. Either revise your app to participate in this system, or drop your targetSdkVersion below 23.
You must get permission for this work like:
for do it impliment this code:
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},23
);
}
}
good luck!!!
Try this code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkPermission()) {
//do your work
} else {
requestPermission();
}
}
}
protected boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
protected void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do your work
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}

Categories

Resources