i need to add an alarm with a preset ringtone and at max volume
but i don't understand how i can pass this info to AlarmClock....
i have the ringtone in my res/raw (inside apk) and i use this code:
Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(AlarmClock.EXTRA_HOUR, oratimer);
i.putExtra(AlarmClock.EXTRA_MINUTES, minutitimer);
i.putExtra(AlarmClock.EXTRA_RINGTONE, saveSong(context, R.raw.song).toString());
i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
context.startActivity(i);
this is the saveSong function:
public Uri saveSong(Context context, int song) {
byte[] buffer = null;
InputStream fIn = context.getResources().openRawResource(song);
int size = 0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return null;
}
String path = Environment.getExternalStorageDirectory()+"/Ringtones/";
String filename = "song" + ".mp3";
boolean exists = (new File(path)).exists();
if (!exists) {
new File(path).mkdirs();
}
exists = (new File(path+filename)).exists();
if (!exists) {
FileOutputStream save;
try {
save = new FileOutputStream(path + filename);
save.write(buffer);
save.flush();
save.close();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(new File(path + filename))));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
return null;
}
}
return Uri.fromFile(new File(path+filename));
}
but the alarm is made with the default ringtone at the default volume (like 70%?)
any hint for solve this?
tnx
I Think this would work for you
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
Related
When I run my app on Android Pie then its work fine, I mean my code for set ringtone and alarm,notification work perfectly but when I run this app on Android 7 (nougat), then alarm and notification is set but ringtone is not. When I click set ringtone then toast message display that ringtone set successfully but when I check it on my phone it still using previous ringtone.
Code for set ringtone:
private void setRingtone() {
AssetFileDescriptor openAssetFileDescriptor;
((AudioManager) getSystemService(AUDIO_SERVICE)).setRingerMode(2);
File file = new File(Environment.getExternalStorageDirectory() + "", this.fNmae);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Uri parse = Uri.parse(this.fPAth);
ContentResolver contentResolver = getContentResolver();
try {
openAssetFileDescriptor = contentResolver.openAssetFileDescriptor(parse, "r");
} catch (FileNotFoundException e2) {
openAssetFileDescriptor = null;
}
try {
byte[] bArr = new byte[1024];
FileInputStream createInputStream = openAssetFileDescriptor.createInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
for (int read = createInputStream.read(bArr); read != -1; read = createInputStream.read(bArr)) {
fileOutputStream.write(bArr, 0, read);
}
fileOutputStream.close();
} catch (IOException e3) {
e3.printStackTrace();
}
ContentValues contentValues = new ContentValues();
contentValues.put("_data", file.getAbsolutePath());
contentValues.put("title", "nkDroid ringtone");
contentValues.put("mime_type", "audio/mp3");
contentValues.put("_size", Long.valueOf(file.length()));
contentValues.put("artist", Integer.valueOf(R.string.app_name));
contentValues.put("is_ringtone", Boolean.valueOf(true));
contentValues.put("is_notification", Boolean.valueOf(false));
contentValues.put("is_alarm", Boolean.valueOf(false));
contentValues.put("is_music", Boolean.valueOf(false));
try {
RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this, RingtoneManager.TYPE_RINGTONE, parse);
Toast.makeText(this, new StringBuilder().append("Ringtone set successfully"), Toast.LENGTH_LONG).show();
} catch (Throwable th) {
Toast.makeText(this, new StringBuilder().append("Ringtone feature is not working"), Toast.LENGTH_LONG).show();
}
}
Code for alarm:
private void setAlarm() {
AssetFileDescriptor openAssetFileDescriptor;
((AudioManager) getSystemService(AUDIO_SERVICE)).setRingerMode(2);
File file = new File(Environment.getExternalStorageDirectory() + "", this.fNmae);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Uri parse = Uri.parse(this.fPAth);
ContentResolver contentResolver = getContentResolver();
try {
openAssetFileDescriptor = contentResolver.openAssetFileDescriptor(parse, "r");
} catch (FileNotFoundException e2) {
openAssetFileDescriptor = null;
}
try {
byte[] bArr = new byte[1024];
FileInputStream createInputStream = openAssetFileDescriptor.createInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
for (int read = createInputStream.read(bArr); read != -1; read = createInputStream.read(bArr)) {
fileOutputStream.write(bArr, 0, read);
}
fileOutputStream.close();
} catch (IOException e3) {
e3.printStackTrace();
}
ContentValues contentValues = new ContentValues();
contentValues.put("_data", file.getAbsolutePath());
contentValues.put("title", "nkDroid ringtone");
contentValues.put("mime_type", "audio/mp3");
contentValues.put("_size", Long.valueOf(file.length()));
contentValues.put("artist", Integer.valueOf(R.string.app_name));
contentValues.put("is_ringtone", Boolean.valueOf(false));
contentValues.put("is_notification", Boolean.valueOf(false));
contentValues.put("is_alarm", Boolean.valueOf(true));
contentValues.put("is_music", Boolean.valueOf(false));
try {
Toast.makeText(this, new StringBuilder().append("Alarm set successfully"), Toast.LENGTH_LONG).show();
// RingtoneManager.setActualDefaultRingtoneUri(getBaseContext(), RingtoneManager.TYPE_RINGTONE, contentResolver.insert(MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath()), contentValues));
RingtoneManager.setActualDefaultRingtoneUri(getBaseContext(), RingtoneManager.TYPE_ALARM, parse);
Settings.System.putString(contentResolver, Settings.System.ALARM_ALERT,
parse.toString());
} catch (Throwable th) {
Toast.makeText(this, new StringBuilder().append("Alarm feature is not working"), Toast.LENGTH_LONG).show();
}
}
I am using the following code, but it doesn't seem to change the ringtone. What am I doing wrong, or is there an easier way to set an mp3 to ringtone? I have a uri that parses the location, and I call the following function. I know the uri is correct because it functions correctly with a file share method I have.
private void setRingtone(Uri uri) {
AssetFileDescriptor openAssetFileDescriptor;
((AudioManager) getActivity().getSystemService(AUDIO_SERVICE)).setRingerMode(2);
File file = new File(Environment.getExternalStorageDirectory() + "/appkeeda", mp3s[position]);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
ContentResolver contentResolver = getActivity().getContentResolver();
try {
openAssetFileDescriptor = contentResolver.openAssetFileDescriptor(uri, "r");
} catch (FileNotFoundException e2) {
openAssetFileDescriptor = null;
}
try {
byte[] bArr = new byte[1024];
FileInputStream createInputStream = openAssetFileDescriptor.createInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
for (int read = createInputStream.read(bArr); read != -1; read = createInputStream.read(bArr)) {
fileOutputStream.write(bArr, 0, read);
}
fileOutputStream.close();
} catch (IOException e3) {
e3.printStackTrace();
}
ContentValues contentValues = new ContentValues();
contentValues.put("_data", file.getAbsolutePath());
contentValues.put("title", "nkDroid ringtone");
contentValues.put("mime_type", "audio/mp3");
contentValues.put("_size", Long.valueOf(file.length()));
contentValues.put("artist", Integer.valueOf(R.string.app_name));
contentValues.put("is_ringtone", Boolean.valueOf(true));
contentValues.put("is_notification", Boolean.valueOf(false));
contentValues.put("is_alarm", Boolean.valueOf(false));
contentValues.put("is_music", Boolean.valueOf(false));
try {
//Toast.makeText(this, new StringBuilder().append("Ringtone set successfully"), Toast.LENGTH_LONG).show();
RingtoneManager.setActualDefaultRingtoneUri(getActivity().getBaseContext(), 1, contentResolver.insert(MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath()), contentValues));
} catch (Throwable th) {
//Toast.makeText(this, new StringBuilder().append("Ringtone feature is not working"), Toast.LENGTH_LONG).show();
}
}
Solution: This tutorial worked for me: http://blog.nkdroidsolutions.com/set-default-ringtone-raw-folder-programmatically-android/
My project has 30 images in drawable & I would like to save/copy all these images to sd card on a button click. I'm using below code to save image to sd card but I don't want to copy paste this code 30 times to save all the images. So is there any better solution for this problem. Thanks
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.aurora);
String fileName = "aurora.png";
File sd = Environment.getExternalStorageDirectory();
File folder = new File(sd + "/Wallpaper Pack");
folder.mkdir();
File dest = new File(folder, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Its very simple, create a array and loop it.
int[] drawablesArr = {R.id.name1, R.id.name2, ....}
for(int i=0l i<=drawablesArr.length; i++){
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), drawablesArr[i]);
String fileName = "image_"+ String.valueOf(i)+".png" ;
File sd = Environment.getExternalStorageDirectory();
File folder = new File(sd + "/Wallpaper Pack");
folder.mkdir();
File dest = new File(folder, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Murtaza Hussain's answer is right but it is better to run such operations out of UI (main) Thread. So, you can use ThreadPoolExecutor:
// SaveThread.java
public class SaveThread implements Runnable {
private int drawable;
private String fileName;
private Context context;
public SaveThread(Context context, int drawable, String fileName) {
this.drawable = drawable;
this.fileName = fileName;
this.context = context;
}
#override
public void run() {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), drawable);
File dest = new File(Environment.getExternalStorageDirectory(), "WallpaperPack/" + fileName);
dest.getParentFile().mkdirs();
try {
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
then inside your activity or in other components:
int core = Runtime.getRuntime().availableProcessors();
ExecutorService executor =
new ThreadPoolExecutor(
core + 1,
core * 2 + 1,
60l,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>()
);
int[] drawables = {R.id.name1, R.id.name2, ....}
for(int drawable : drawables) {
executor.execute(new SaveThread(getApplicationContext(), drawable, "image_"+ drawable +".png"));
}
executor.shutdown();
I have a listview with just a text when I press that item the song play. That is working very well, but when I press onItemLongClick() I need that song set as a ringtone.
I eddited the code. Now my problem is now, when i press itemlongclick the result is the else "No se pudo asignar como ringtone" (could not assign as ringtone)
All songs are in raw resources.
public class MainActivity extends Activity {
MediaPlayer mp = new MediaPlayer();
ListViewAdapter adapter;
int s1[] =
{
R.raw.el_tri_abuelita_soy_tu_nieto,
R.raw.el_tri_ahi_te_lo_lavas,
R.raw.el_tri_bajate_del_avion,
};
int position;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list30 = (ListView) findViewById(R.id.list);
ArrayList<String> items = new ArrayList<String>();
items.add("Abuelita soy tu nieto");
items.add("Ahi te lo lavas");
items.add("Bajate del avion");
adapter = new ListViewAdapter(this, items );
list30.setAdapter(adapter);
list30.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
method(position); //play de song normaly, this work well
}
});
Log.i("ramiro", "onClickListener");
list30.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if(saveas(R.raw.el_tri_abuelita_soy_tu_nieto, "examplename") == true)
Toast.makeText(getApplication(), "Se asigno como ringtone", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "No se pudo asignar como ringtone", Toast.LENGTH_SHORT).show(); //out over here
return false;
}
});
}
public boolean saveas(int ressound, String soundName)
{
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/media/audio/ringtones/";
String filename=soundName+".mp3";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
I followed a couple tutorials on setting ringtones and notifications and this is what i ended up with. You call the saveas() method and pass it a sound in your raw folder and then A String soundName , which will be the title of the sound listed when you pick a ringtone. The method will return false if failed, and true if it worked. Also in the android manifest you need to allow;
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.WRITE_SETTINGS"
uses-permission android:name="android.permission.CHANGE_CONFIGURATION"
uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"
Also make sure to change the code as needed if you are using something other than .mp3
saveas(R.raw.examplesound, "examplename")
public boolean saveas(int ressound, String soundName)
{
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/media/audio/ringtones/";
String filename=soundName+".mp3";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path + filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, soundName);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "artistname ");
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);
//Work with the content resolver now
//First get the file we may have added previously and delete it,
//otherwise we will fill up the ringtone manager with a bunch of copies over time.
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
this.getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
//Ok now insert it
Uri newUri = this.getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri( this,RingtoneManager.TYPE_RINGTONE,newUri);
I want to save a captured image in an SD-card specific folder with current time mills name of the image.
How can I do this?
try this after getting the bitmap object
private void save_Image_to_sdcard() {
// TODO Auto-generated method stub
OutputStream file_outputstream = null;
InputStream in = null;
try {
URL path = new URL(url);
in = path.openStream();
String path1 =
Environment.getExternalStorageDirectory().toString();
System.out.println(path1+ " " +user_file_name);
// /mnt/sdcard
File f = new File(path1 + "/"+System.currentTimeMillis()+".png");
f.createNewFile();
System.out.println("file created " + f.toString());
file_outputstream = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer, 0, buffer.length)) >= 0) {
file_outputstream.write(buffer, 0, bytesRead);
}
file_outputstream.close();
in.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("hey", "error");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("hey", " ioexception");
}
}
Save file as following way,
fileName + DateFormat.format( ConstantCodes.dd_MMM_yyyy_kk_mm_ss ,new java.util.Date()).toString() + ".jpg";
private Uri saveToFileAndUri() throws Exception{
long currentTime = System.currentTimeMillis();
String fileName = "MY_APP_" + currentTime+".jpg";
File extBaseDir = Environment.getExternalStorageDirectory();
File file = new File(extBaseDir.getAbsoluteFile()+"/MY_DIRECTORY");
if(!file.exists()){
if(!file.mkdirs()){
throw new Exception("Could not create directories, "+file.getAbsolutePath());
}
}
String filePath = file.getAbsolutePath()+"/"+fileName;
FileOutputStream out = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, out); //control the jpeg quality
out.flush();
out.close();
long size = new File(filePath).length();
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, fileName);
// That filename is what will be handed to Gmail when a user shares a
// photo. Gmail gets the name of the picture attachment from the
// "DISPLAY_NAME" field.
values.put(Images.Media.DISPLAY_NAME, fileName);
values.put(Images.Media.DATE_ADDED, currentTime);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.ORIENTATION, 0);
values.put(Images.Media.DATA, filePath);
values.put(Images.Media.SIZE, size);
return ThisActivity.this.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}