Android 6.0 Permissions Issues - android

I am having one heck of a time with this new permission request in Android 6. My app worked fine, and then in the last two days it is force closing all the time. If I change the target SDK level to 22, it works fine, but of course Play Store wont let you downgrade the SDK.
I need these permissions.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.android.vending.BILLING" />
After this I am not sure how to work the requesting, or new way of implementing the permissions part so the errors will stop. I have been working on this for hours and have googled and search endlessly. While alot of examples out there all tell me to do the same thing, I just cannot seem to get it write in Android Studio. Any help would be greatly appreciated.
Here is part of the code that was giving me issues.
public void exportSkin(View arg0) throws IOException {
if (type.equals("popular")) {
AssetManager assetManager = getAssets();
InputStream is = assetManager.open("skins/" + skinname + ".png");
// create a File object for the parent directory
File wallpaperDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath() + "/SkinYourself/");
// have the object build the directory structure, if needed.
//noinspection ResultOfMethodCallIgnored
wallpaperDirectory.mkdirs();
// create a File object for the output file
File out = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/SkinYourself/", "" + PopChar.character_name + ".png");
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(out);
int read;
while ((read = is.read(buffer, 0, 1024)) >= 0) {
fos.write(buffer, 0, read);
}
fos.flush();
fos.close();
is.close();
}
if (type.equals("create")) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/SkinYourself");
myDir.mkdirs();
String fname = "SkinYourself" + System.currentTimeMillis() / 1000 + ".png";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
*/
Toast.makeText(MainActivity.this,
"Your skin has been saved to the SkinYourself folder check the info button on how to use it", Toast.LENGTH_LONG)
.show();
displayInterstitial();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
}
}

Related

No file directory : java.io.IOException: No such file or directory

I'm working on an Android project and i wanna get the path of the uploaded picture from Camera or Gallery. All the permissions are set and I use this function to get the path but it seems createNewFile() is always ignored and i get path="" all the time.
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
but i get a problem on the log
There could be something the way you put together your filepath, but this is not viewable by your post. You could have missed giving permissions in the manifest, so the file is not created.
Try this:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
Make sure you have an External SD card in your phone as you are trying to access
Environment.getExternalStorageDirectory()

Download/Install apk Version 23>

After reading multiple post concerning this subject I have been able to put together the info needed to download an update for my apk and have it install. This is successful for versions under 23. After reading more post I discovered for versions 23> there is a slight difference in the way to execute the install. I have put together this info in the following code but I am still encountering a problem with the version 23>. I pretty much understand what the code is doing, but I have no idea why it fails to run.
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() +"/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "maga.apk");
if(outputFile.exists()){
Log.i("SCROLLS ", "file exist-delete");
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
if(outputFile.exists()){
Log.i("SCROLLS ", "file exist");
}
if (Build.VERSION.SDK_INT >= 23) {
File toInstall=new File(Uri.parse(PATH+"maga.apk").getPath());
Log.i("SCROLLS ", "toInstall "+ toInstall);
Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", toInstall);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
} else {
File toInstall = new File(PATH, "maga" + ".apk");
Uri apkUri = Uri.fromFile(toInstall);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
} catch (Exception e) {
Log.e("SCROLLS ", "Update error! " + e.getMessage());
}
return null;
}
}
When executed on an emulator with Version <23 all works. On an emulator over 23, the progress gets into the If statement and sets the toInstall value but nothing happens after that. The only thing I see in Logcat resembling and error that pertains to this is
03-24 01:35:16.562 5300-5300/com.google.android.packageinstaller E/InstallStart: Requesting uid 10079 needs to declare permission android.permission.REQUEST_INSTALL_PACKAGES
Looking into this it's my understanding that this permission is for system apps so adding it to Manifest does no good. Is there something missing from my code or a permission? I have added the provider to the manifest and the provider_paths.xml file to the project. Thanks for any help.

Getting No such file or Directory on some Android versions only

I am very much confused with my code it is because of the FileOutputStream seems to find a file on Android 8.0 and 5.0. However, on other Android versions such as Android 4.0, 6.0, 7.0, it gives me a No such file or directory (java.io.FileNotFoundException).
This is my block of code:
try{
File appFolder = new File(Environment.getExternalStorageDirectory() + "/" + Constants.DEFAULT_FOLDER);
if (!appFolder.exists()){
appFolder.mkdir();
}
File imageFile = new File(Environment.getExternalStorageDirectory() + "/" + Constants.DEFAULT_FOLDER + "/" + mShortName);
if (!imageFile.exists()){
URL url = new URL(mImageUrl);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
FileOutputStream out = new FileOutputStream(imageFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
}
Log.i("error", "" + imageFile.getAbsolutePath());
share(imageFile.getAbsolutePath());
}
catch (Exception e){
e.printStackTrace();
mRespHandler.sendEmptyMessage(Constants.RESPONSE_SET_WALLPAPER_ERROR);
}
So, I am receiving the FileNotFoundException on this line: FileOutputStream out = new FileOutputStream(imageFile);
I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> on my Manifest.
What can be the problem with this one?
Google documenation states you can call Environment.getExternalStorageState to make sure the external storage is available.

Error to Create folder on SD card under DCIM folder in Android

I know this is duplicate question but there is not available any solution for this. I have used latest API Level 24 and Test on API 23. I have to save image on SD Card with my App Name folder but folder is not created...
I have write following method but it not working
public void actionScreenShot(View view) {
//enable drawing cache true
imageContainer.setDrawingCacheEnabled(true);
imageContainer.buildDrawingCache(true);
//create image from layout
Bitmap bitmap = Bitmap.createBitmap(imageContainer.getDrawingCache());
//String folder_path = getApplicationContext().getFilesDir().getPath() + "/MyAppTest/"; //It's work properly
//String folder_path = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DCIM) + "/MyAppTest/"; //It's work properly
String folder_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "/MyAppTest"; //It's not work properly
if (checkFile(folder_path)) {
saveFile(new File(folder_path), bitmap);
} else {
File folder = new File(folder_path);
if (folder.mkdirs()) {
saveFile(folder, bitmap);
} else {
Log.d("Directory", " >> not created");
}
}
}
public void saveFile(File folder, Bitmap bitmap) {
boolean success = false;
try {
File file = new File(folder, "temp.png");
if (file.exists()) file.delete();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
success = checkDatabase(file.getPath());
}catch (Exception e) {
e.printStackTrace();
}
if (success) {
Log.d("FILE", "success");
} else {
Log.d("FILE", "not success");
}
}
public boolean checkFile(String myPath) {
boolean isExist = false;
try {
File file = new File(myPath);
isExist = file.exists();
} catch (Exception e) {
}
return isExist;
}
Permission is given also in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Log Trace as following...
10-05 17:08:09.424 2808-2808/packagename D/Directory >> not created
If any solution available then help me...
Thanks....
here is the simple code to create folder in sdcard
// create a File object for the parent directory
File newFolder = new File("/sdcard/newFolder/");
// have the object build the directory structure, if needed.
newFolder.mkdirs();
// create a File object for the output file
File outputFile = new File(newFolder, filename);
// now attach the OutputStream to the file object, instead of a String
FileOutputStream fos = new FileOutputStream(outputFile);
permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The problem is that you are using API 23 and 24 (Marshmallow).
Google changed the permission strategy from API 23.
Reduce your target version to 22. It will work. If you want 23 or 24 then include code to request permission at run time.

Android - Copy res/raw resource to SD correctly

Well, I tried a lot of things, but the better goal that I achieve is copy the desired file to sd, but the new file size is 0bytes always :(
This is my code :
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = sonidoActual+".mp3";
File newSoundFile = new File(baseDir, fileName);
Uri mUri = Uri.parse("android.resource://com.genaut.ringtonelists/raw/"+sonidoActual);
AssetFileDescriptor soundFile;
try {
soundFile= getContentResolver().openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile=null;
}
try {
byte[] readData = new byte[1024*500];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
Log.d("Degug - While: ", "i: "+i);
}
fos.flush();
fos.close();
} catch (IOException io) {
}
Sorry for my bad english.Any one know the problem? Thanks a lot!
I have these permissions on my manifest:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
More info:
I tried some code to copy files from assets and not work.. I have some app that set Ringtone well, so I don't think that my SD has a problem.. I feel hopeless :S
These are the code from assets, apparently works fine: https://stackoverflow.com/a/4530294/1422434
I tried too with getResources.openRawResource(): but not works
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = nombreActual+".mp3";
File newSoundFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024*500];
InputStream fis = getResources().openRawResource(contexto.getResources().getIdentifier(sonidoActual,"raw", contexto.getPackageName()));
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
As you are using the raw folder, simply use this from your activity:
getResources().openRawResource(resourceName)

Categories

Resources