I'd like to set a raw mp3 file, which is located in my raw folder, as the device ringtone (using java). Unfortunately the old tutorials do not work anymore, often because you need some write permissions. I tried everything out there, but no solution works (the solutions are all veery old...).
Can anyone help me please? Has anyone a good code example for that problem?
If you dont mind putting your file in assets folder then you can do this :
copy your mp3 from assets to device accessible memory
set the new copied file as ringtone using
void set_asset_ringtone(Context context, String output_file_path, String asset_name) throws IOException {
///////////////copying from assets to filepath////////////////
InputStream externalDbStream = context.getAssets().open(asset_name);
String outFileName =output_file_path+"/"+asset_name;
OutputStream localDbStream = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = externalDbStream.read(buffer)) > 0) {
localDbStream.write(buffer, 0, bytesRead);
}
localDbStream.close();
externalDbStream.close();
//////Setting the ringtone /////////////////
File rigntone_file=new File(outFileName);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, rigntone_file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "ring");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, rigntone_file.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, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(rigntone_file.getAbsolutePath());
Uri newUri = getContentResolver().insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
} catch (Throwable t) {
}
}
You will need these permisions
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And maybe
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
Related
How to save bitmap to image file? (png/jpg any types don't care...)
I'm running device(hisilicon) & android app.
Android and device are communicating over sockets.
Device send Image (h.264) and show it on Android on TextureView.
I can get Bitmap from TextureView, using textureView.getBitmap().
I made a button button to save the picture, textureView.getBitmap().
<Button
android:id="#+id/btnSavePng"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onBtnSavePng"
android:text="savePicture" />
and, onclick function is like under.
public String getCurrentTimeString() {
int yyyy = Calendar.getInstance().get(Calendar.YEAR);
int MM = Calendar.getInstance().get(Calendar.MONTH) + 1;
int dd = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int hh = Calendar.getInstance().get(Calendar.HOUR);
int mm = Calendar.getInstance().get(Calendar.MINUTE);
int ss = Calendar.getInstance().get(Calendar.SECOND);
String result = yyyy+"-"+MM+"-"+dd+" "+hh+":"+mm+":"+ss;
return result;
}
public void onBtnSavePng(View view) {
try {
File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String fname = getCurrentTimeString() + ".jpg";
File tp = new File(storage, fname);
Bitmap bm = textureView.getBitmap();
tp.createNewFile(); // Result of File.createNewFile() ignored
FileOutputStream ot = new FileOutputStream(tp);
bm.compress(Bitmap.CompressFormat.JPEG, 100, ot);
ot.close();
} catch(Exception e) {
Log.d("onBtnSavePng", e.toString()); // java.io.IOException: Operation not permitted
}
}
I allow uses-permissions AndroidManifest.xml like under, and android:requestLegacyExternalStorage="true" is on application.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Is there any problem with my codes?
If so, how to save bitmap to png or jpg file?
I guess, my app don't access to directory.
Thank you for read my question.
Self Solved.
public void onBtnSavePng(View view) {
try {
String root = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = getCurrentTimeString() + ".jpg";
File file = new File(myDir, fname);
FileOutputStream out = new FileOutputStream(file);
Bitmap bm = textureView.getBitmap();
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch( Exception e) {
Log.d("onBtnSavePng", e.toString());
}
I don't understand why my code is worked not yet.
Anyway, Thank you for all who helps me.
I'll try all of reply codes.
Thank you.
1.Check it if you don't request the runtime permission yet: https://developer.android.com/training/permissions/requesting
2.Or if your android is higher than 10:
https://developer.android.com/about/versions/11/privacy/storage#scoped-storage
After you update your app to target Android 11, the system ignores the requestLegacyExternalStorage flag.
Then you have to use SAF or MediaStore API to store the bitmap in the "public directory".
SAF:
https://developer.android.com/guide/topics/providers/document-provider
MediaStore API:
https://developer.android.com/reference/android/provider/MediaStore
public void onBtnSavePng(View view) {
try {
String fileName = getCurrentTimeString() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/");
values.put(MediaStore.MediaColumns.IS_PENDING, 1);
} else {
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File file = new File(directory, fileName);
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
}
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try (OutputStream output = getContentResolver().openOutputStream(uri)) {
Bitmap bm = textureView.getBitmap();
bm.compress(Bitmap.CompressFormat.JPEG, 100, output);
}
} catch (Exception e) {
Log.d("onBtnSavePng", e.toString()); // java.io.IOException: Operation not permitted
}
}
In kotlin
This is working for me->
fun saveMediaToStorage(bitmap: Bitmap, context: Context, onUriCreated: (Uri) -> Unit) {
var fos: OutputStream? = null
//Generating a file name
val filename = "${System.currentTimeMillis()}.jpg"
try {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
val resolver = context.contentResolver
val contentValues = ContentValues()
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "$filename.jpg")
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg")
val imageUri =
resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
fos = Objects.requireNonNull(imageUri)?.let {
resolver.openOutputStream(it)
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
Objects.requireNonNull(fos)
imageUri?.let { onUriCreated(it) }
} else {
//These for devices running on android < Q
val imagesDir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val image = File(imagesDir, filename)
fos = FileOutputStream(image)
fos.use {
//Finally writing the bitmap to the output stream that we opened
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
}
onUriCreated(Uri.fromFile(image))
}
} catch (e: Exception) {
Log.d("error", e.toString())
}
}
String myDir =new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+pdfDirectoryImage);
fileName = filename + ".png";
androidElevenPath = saveImages(mContext,finalBitmap,filename);
private static Uri saveImages(Context mContext, Bitmap bitmap, #NonNull String name) throws IOException {
boolean saved;
OutputStream fos;
File image = null;
Uri imageUri = null;
String imagesDir = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = mContext.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM" + pdfDirectoryImage);
imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = resolver.openOutputStream(imageUri);
} else {
imagesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).toString() + File.separator + pdfDirectoryImage;
File file = new File(imagesDir);
if (!file.exists()) {
file.mkdir();
}
image = new File(imagesDir, name + ".png");
fos = new FileOutputStream(image);
}
saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
return imageUri;
}
In case you are on Android11+ and you have the storage manager permission granted and are working directly with files (and not the MediaStore API) the cause could be a ":" char (usually from a timestamp) in the name of the created file. Android 11 (unlike older Android versions) does not allow that.
I'm fairly new into saving media in android, and I'm wondering why this is giving me so much trouble. I am requiring photos taking by my app to be made public, so other apps (including the gallery) can find them.
The documentation states that it if you want an image to be accessible by other apps, you should save them on in the public external storage which is provided by getExternalStoragePublicDirectory(), with the DIRECTORY_PICTURES as the argument.
When I try to do this however, the IOException is thrown in my method, and I'm struggling to find out why.
File creation method:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
Photo capture method:
public void capturePhoto (View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, "com.auswide.auswidedashboard", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, IMAGE_REQUEST);
}
}
}
Permissions and Provider code in the Manifest
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.auswide.auswidedashboard"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"/>
</provider>
And finally the path required by the provider:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="my_images" path="Android/data/com.auswide.auswidedashboard/files/Pictures"/>
</paths>
The exception message reads I/System.out: java.io.IOException: Permission denied', which simply confuses me more as I though I gave it the permissions in the manifest?
Any help would be greatly appreciated.
EDIT: Facebook issue : https://developers.facebook.com/support/bugs/2434932356771915/
I'm trying to share a bitmap to an Instagram story sticker.
But it loads Instagram, but doesn't show any sticker, no background colors, only a black story screen.
What is wrong with this code ? I check if file was in the external data cache directory and that's good.
According to Facebook's Instagram documentation :
I added read/write rights to storage and a provider to my AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<provider
android:authorities="my.app.id.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
I added a file_paths.xml to share my external cache folder to other apps
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-cache-path name="share" path="."/>
</paths>
</resources>
I create a bitmap from a drawable, write it to a file on the external cache dir, and apply the Intent like example in the docs
public static void sendStickerToInstagram() {
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.sticker);
File extStorageDirectory = context.getExternalCacheDir();
File stickerFile = new File(extStorageDirectory, "sticker.png");
try {
FileOutputStream outStream = new FileOutputStream(stickerFile);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (IOException e) {
Log.e("TEST", e.getMessage());
}
Uri stickerUri = FileProvider.getUriForFile(activity, "my.app.id.fileprovider", stickerFile);
// Uri stickerUri = Uri.fromFile(stickerFile);
String linkUrl = "https://stackoverflow.com";
Intent intent = new Intent("com.instagram.share.ADD_TO_STORY");
intent.setType("image/*");
intent.putExtra("interactive_asset_uri", stickerUri);
intent.putExtra("content_url", linkUrl);
intent.putExtra("top_background_color", "#33FF33");
intent.putExtra("bottom_background_color", "#FF00FF");
grantUriPermission("com.instagram.android", stickerUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (getPackageManager().resolveActivity(intent, 0) != null) {
startActivityForResult(intent, 0);
}
}
Most strange part is when I test to share my sticker as background, it works, so the file is loaded as espected, with all permissions.
Intent intent = new Intent("com.instagram.share.ADD_TO_STORY");
intent.setDataAndType(stickerUri, "image/*");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra("content_url", linkUrl);
if (activity.getPackageManager().resolveActivity(intent, 0) != null) {
activity.startActivityForResult(intent, 0);
}
Any idea why I can't share a sticker ?
Don't worry... It's not you. It's Instagram. :P
Their most recent release of Instagram on Android broke the
com.instagram.share.ADD_TO_STORY intent.
Keep an eye on this thread for updates.
https://developers.facebook.com/support/bugs/2434932356771915/
When I click on my button I can select the photo and it shows in my imageView.
But when I click to save, my imageView has become NULL. Anyone can help me?
Bitmap always comes null.
I changed
Bitmap bitmap =
((BitmapDrawable)imageViewProeto.getDrawable()).getBitmap();
to
Bitmap bitmap = imageViewProeto.getDrawingCache();
https://i.stack.imgur.com/S7gcN.jpg
BitmapDrawable draw = (BitmapDrawable) iv.getDrawable();
Bitmap bitmap = draw.getBitmap();
To save Image in Your Gallery :
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/YourFolderName");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Refresh Gallery :
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
And Dont Forget to add permission in your Menifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am building an android app which depends on the other application ,actually the other application is the writing pad which I want to install with the application,I am trying to place the apk file inside the raw folder and trying to access it like this:
Uri app= Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.app);
Is it feasible? If yes how can I install this app?
Place your apk in asset folder and change myAPKFile.apk to your apk file name and use this function to install your apk.
Permissions required:
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
private boolean InstallmyAPK(){
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File myAPKFile = new File(Environment.getExternalStorageDirectory().getPath()+"/myAPKFile.apk");
try {
if(!myAPKFile.exists()){
in = assetManager.open("myAPKFile.apk");
out = new FileOutputStream(myAPKFile);
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(myAPKFile),
"application/vnd.android.package-archive");
startActivity(intent);
return true;
} catch(Exception e) {return false;}
}
try (I think this question has already been answered before here: Install Application programmatically on Android)
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.parse("file:///path/to/your.apk"),
"application/vnd.android.package-archive");
startActivity(promptInstall);