I use this below code but is working only down to android 10.
This is how I save the audio file.
File ringtoneuri = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES);
Random r = new Random();
int i1 = r.nextInt(450 - 280) + 280;
File newSoundFile = new File(ringtoneuri, name+i1+".mp3");
Uri mUri = Uri.parse(path);
The file is saved DIRECTORY_RINGTONES.
ContentResolver mCr = v.getContext().getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile = mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile = null;
}
try {
byte[] readData = new byte[1024];
assert soundFile != null;
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);
}
fos.close();
} catch (IOException ignored) {
}
My file is set as ringtone but is not working( I got something like 12165016516 instead of the sound name, in sound settings, this is happening only in android 11 )
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, newSoundFile.getName());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
values.put(MediaStore.MediaColumns.SIZE, newSoundFile.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(newSoundFile.getAbsolutePath());
Uri newUri = mCr.insert(uri, values);
Toast.makeText(v.getContext(),"Sound was set!",Toast.LENGTH_SHORT).show();
Every think is working i don t have erros.
try {
if (checkSystemWritePermission()) {
RingtoneManager.setActualDefaultRingtoneUri(popUp.this, RingtoneManager.TYPE_RINGTONE, newUri);
Toast.makeText(popUp.this, "Set as Ringtone successfully! ", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(popUp.this, "Allow modify system settings ==> ON ", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.i("rington",e.toString());
Toast.makeText(popUp.this, "Unable to set as Ringtone! ", Toast.LENGTH_SHORT).show();
}
I'm mentioning that requestLegacyExternalStorage is set to "true" in my manifert.xml file.
What is the problem Please Help!!
Related
Im working on an app and I need to set an mp3 file thats is include in the app as a ringtone.
The following code works well in debug mode (im testing on Android 11), but in the phone the seted ringtone name is a string numbers. Also i can't play the saved file on my phone.
If anyone knows the reason for this behavior I would appreciate your help :)
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pathi=Environment.getExternalStorageDirectory().getPath();
boolean exists = (new File(pathi)).exists();
if (!exists) {
new File(pathi).mkdirs();
}
File file_aux = new File(pathi, "name.mp3");
Uri mUri = Uri.parse("android.resource://com.package.name/"+R.raw.name);
ContentResolver mCr = getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile = mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile = null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(file_aux);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
Log.e("harrypopoter", io.getMessage());
io.printStackTrace();
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.TITLE, file_aux.getName());
values.put(MediaStore.MediaColumns.MIME_TYPE, getMIMEType(file_aux.getPath()));
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.MediaColumns.SIZE, file_aux.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Uri newUri = getContentResolver()
.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
try (OutputStream os = getContentResolver().openOutputStream(newUri)) {
int size = (int) file_aux.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file_aux));
buf.read(bytes, 0, bytes.length);
buf.close();
os.write(bytes);
os.close();
os.flush();
} catch (IOException e) {
Log.e("harrypopoter", e.getMessage());
e.printStackTrace();
}
} catch (Exception ignored) {
Log.e("harrypopoter", ignored.getMessage());
ignored.printStackTrace();
}
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
}
}
});
I can not open a pdf file on andorid Q I do this :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
OutputStream fosTemp;
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Files.FileColumns.DISPLAY_NAME, "mamy123");
contentValues.put(MediaStore.Files.FileColumns.MIME_TYPE, "application/pdf");
contentValues.put(MediaStore.Files.FileColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
Uri imageUri2 = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
fosTemp = resolver.openOutputStream(imageUri2);
byte[] pdfAsBytes = Base64.decode(base64, 0);
fosTemp.write(pdfAsBytes);
fosTemp.flush();
fosTemp.close();
openPDF(context, imageUri2);
}
I see a black screen and in logs I have :
java.lang.SecurityException: com.google.android.apps.docs has no access to content://media/external/downloads/49
public static void openPDF(Context context, Uri localUri) {
Intent i = new Intent( Intent.ACTION_VIEW );
i.setDataAndType( localUri, PDF_MIME_TYPE );
context.startActivity( i );
}
This is how I open pdf file on android Q I see a black file , a file is on folder Download
This is working for me. Tested on Android R (11). Create and save a PDF in the Downloads folder on Android Q (10) & R. I use this library to generate PDFs:
implementation 'com.uttampanchasara.pdfgenerator:pdfgenerator:1.3'
Create the PDF and call the writeFileToDownloads method in the OnSuccess callback. As a bonus, a download notification is created:
String root = mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();
File file = new File(root, documentTitle + ".pdf");
if (root != null) {
new CreatePdf(mContext)
.setPdfName(documentTitle)
.openPrintDialog(false)
.setContentBaseUrl(null)
.setPageSize(PrintAttributes.MediaSize.ISO_A4)
.setContent(documentContent)
.setFilePath(root)
.setCallbackListener(new CreatePdf.PdfCallbackListener() {
#Override
public void onFailure(String s) {
Toast.makeText(mContext, mContext.getResources().getString(R.string.toast_an_error_occurred), Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(String s) {
DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
downloadManager.addCompletedDownload(file.getName(), file.getName(), true, "application/pdf", file.getAbsolutePath(), file.length(), true);
writeFileToDownloads(file);
}
})
.create();
To save the PDF in the downloads folder, call the writeFileToDownloads method. This will check the that the Android version is greater than or equal to Q:
private void writeFileToDownloads(File file) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = mContext.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, file.getName());
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
Uri uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
try {
int size = (int) file.length();
byte[] bytes = new byte[size];
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
OutputStream fos = resolver.openOutputStream(uri);
fos.write(bytes);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hello I am tring to open a .pdf file present in a file using an intent but it is giving me 2 errors on the following line
File file = new File(getContext().getAssets().open("assets/test.pdf"));
Errors
1.Unhandled java.IO.Exception.
2.getAssets()may produce java.lang.NullPointerException
Here us the code in a fragment
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
File file = new File(getContext().getAssets().open("assets/test.pdf"));
if (file .exists())
{
Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(pdfIntent ); }
catch (ActivityNotFoundException e)
{
Toast.makeText(getActivity(), "Please install a pdf file viewer",
Toast.LENGTH_LONG).show();
}
}
}
}
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
getApplicationContext().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(SecondActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase("abc.pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card
try with the file provider
Intent intent = new Intent(Intent.ACTION_VIEW);
// set flag to give temporary permission to external app to use your FileProvider
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open
String uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file);
// I am opening a PDF file so I give it a valid MIME type
intent.setDataAndType(uri, "application/pdf");
// validate that the device can open your File!
PackageManager pm = getActivity().getPackageManager();
if (intent.resolveActivity(pm) != null) {
startActivity(intent);
}
To serve a file from assets to another app you need to use a provider.
Google for the StreamProvider of CommonsWare.
I got an error in console crashes & anrs. This error is showing sometimes and I couldn't find where the problem is.
java.lang.NullPointerException
at java.io.File.fixSlashes(File.java:185)
at java.io.File.<init>(File.java:134)
The function code to save picture is:
public static String sharePhoto(Context context, Bitmap bmp) {
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Folder");
boolean success = true;
String file_path = null;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
file_path = folder + "/Img_" + System.currentTimeMillis() / 1000 + ".jpg";
}
OutputStream os = null;
try {
os = new FileOutputStream(file_path);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Do something else on failure
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(file_path);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
return file_path;
}
Try this:
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/MyFolder");
Thing is that getExternalStorageDirectory() returns File. You need to get absolute path of that file and concatenate with "/Pictures/MyFolder".
To share the image via Email and mms first step I need to save the image in sdcard but for me the saved image is not getting opened instead "Invalid File" error, I checked with the extension format everything is correct but don't know where I'm going wrong.
Below is the java code.
public class Share extends CordovaPlugin {
public static final String ACTION_POSITION = "ShareImage";
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
throws JSONException {
if (ACTION_POSITION.equals(action)) {
try {
JSONObject arg_object = args.getJSONObject(0);
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("image/jpg");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, arg_object.getString("image"));
String name = arg_object.getString("image");
String defType = "drawable";
String defPackage = "com.picsswipe";
int drawableId = this.cordova.getActivity().getResources().getIdentifier( name , defType, defPackage );
// Bitmap bbicon = BitmapFactory.decodeFile( arg_object.getString("image") );
Bitmap bbicon = BitmapFactory.decodeResource( this.cordova.getActivity().getResources(),drawableId );
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File f = new File(extStorageDirectory + "/Download/",
"jj.jpg" );
try {
outStream = new FileOutputStream(f);
bbicon.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
}
File r1 = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Download/", "jj.jpg");
//RETRIEVING IMAGES FROM SDCARD
Uri uri1 = Uri.fromFile(r1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri1);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(r1));
Uri uris = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "jj.jpg"));
this.cordova.getActivity().startActivity(sendIntent);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
return true;
}
}
File file;
File rootPath = android.os.Environment
.getExternalStorageDirectory();
File directory = new File(rootPath.getAbsolutePath()
+ "/Download");
if (!directory.exists())
directory.mkdir();
file = new File(directory, "filename.PNG");//.png/.jpg anything you want
try {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.pincheck);
FileOutputStream outStream;
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and you should add this permission in your manifest file..Then only file will copied to your external sd card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>