Regarding Notification Sound In Android - android

In this question,actually i want to change the notification sound.For this i create a custom sound dialog box through which i can change and set the different ringtones.But the problem is that this sound dialog box is present in different activity i.e. SoundActivity while i write the notification code in different activity.Can you please tell me how can i use this sound activity in notification code so that by changing the ringtones,notification sound alos get changed. I have this sound activity in which i set the ringtones according to my demand.But i want these ringtones to be beep when notifications come.I write the code for notifictaion in another activity.Can you please tell me how can i use this sound activity,so that changes made in this activity changes the notification sound???
protected void onCreate(Bundle savedInstanceState)
{
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sound);
setTitle("Sounds");
initUpdateView();
isSystemRingtone=PreferencesClass.getSystemRingtoneStatus(getApplicationContext());
textviewRingtone = (TextView)findViewById(R.id.textview_ringtone_settings);
if(PreferencesClass.getRingtone(getApplicationContext()).substring(0, 1).equalsIgnoreCase("/")){
String[] son=PreferencesClass.getRingtone(getApplicationContext()).split("/");
String[] s=son[son.length-1].split("\\.ogg");
String rep=s[0].replace("_", " ");
if(rep.startsWith("S ")){
rep=rep.substring(2);
}
textviewRingtone.setText(UppercaseFirstLetters(rep));
mysong=son[son.length-1];
mysongPath=PreferencesClass.getRingtone(getApplicationContext());
if(mysongPath.contains("system")){
SelectedTone="Sounds";
}
else{
SelectedTone="My Music";
}
}
songURI=PreferencesClass.getUri(getApplicationContext());
LinearLayout layoutRingtone = (LinearLayout)findViewById(R.id.linearlayout_ringtone_settings);
layoutRingtone.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(RINGTONE_DIALOG_ID);
}
});
}catch(Exception ex)
{
Log.e("ERROR",ex.toString());
}
}
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case RINGTONE_DIALOG_ID:
{
int selectedIndex = 1;
//if(SelectedTone.equalsIgnoreCase("My Music"))
//if(SelectedTone.equalsIgnoreCase(""))
// selectedIndex=0;
Dialog dialog=null;
//final String[] ringArray=new String[]{"My Music","Sounds"};
final String[] ringArray=new String[]{"Sounds"};
if(ringArray.length>0){
AlertDialog.Builder builder = new AlertDialog.Builder(SoundActivity.this);
builder.setSingleChoiceItems(ringArray, selectedIndex, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(which==0){
isSystemRingtone=1;
SelectedTone="Sounds";
PreferencesClass.setSystemRingtoneStatus(1, getApplicationContext());
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Sounds");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,RingtoneManager.TYPE_RINGTONE);
String uri = songURI;
Log.d("uri", uri);
//chooses and keeps the selected item as a uri
if ( uri != null ) {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse( uri ));
} else {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri)null);
}
startActivityForResult(intent,999);
}
dialog.dismiss();
}
});
builder.setTitle("Ringtone");
//dialog=new Dialog(SettingsGroup.group, R.style.Theme_D1dialog);
dialog=builder.create();
dialog.setCanceledOnTouchOutside(true);
return dialog;
}
else
Toast.makeText(getApplicationContext(), "No Data is available", Toast.LENGTH_LONG).show();
}
}
return super.onCreateDialog(id);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("req", requestCode+"");
if (resultCode == RESULT_OK) {
if (requestCode == RQS_OPEN_AUDIO_MP3) {
audioFileUri = data.getData();
Log.d("uri", audioFileUri.toString());
String son[]=audioFileUri.toString().split("/");
int k=0;
int id=1;
try{
id=Integer.parseInt(son[son.length-1]);
}
catch(Exception e){
k=1;
mysong=son[son.length-1];
mysongPath=audioFileUri.getPath();
}
//Log.d("id", son[son.length-1]);
if(k==0){
Uri allaudiosong = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String audioID = data.getDataString();
Uri MyUri = Uri.parse(audioID);
String audioselection = MediaStore.Audio.Media.IS_MUSIC + " !=0 ";
Cursor cursor;
cursor = managedQuery(MyUri, STAR, null, null, null);
int i=0;
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
System.out.println("Audio Song Name= "+song_name);
// mysong[i]=song_name;
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
System.out.println("Audio Song ID= "+song_id);
if(id==song_id){
mysong=song_name;
if(SelectedTone.equalsIgnoreCase("My Music")){
textviewRingtone.setText(mysong);
}
}
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
System.out.println("Audio Song FullPath= "+fullpath);
if(id==song_id){
mysongPath=fullpath;
Log.d("path", fullpath);
if(SelectedTone.equalsIgnoreCase("My Music"))
PreferencesClass.setRingtone(mysongPath, SoundActivity.this);
}
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
System.out.println("Audio Album Name= "+album_name);
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
System.out.println("Audio Album Id= "+album_id);
Log.d("Audio Album Id= ",""+album_id);
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
System.out.println("Audio Artist Name= "+artist_name);
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("Audio Artist ID= "+artist_id);
i++;
} while (cursor.moveToNext());
}
}
}
Log.d("audio",audioFileUri.getPath());
}
if(requestCode==999){
Log.d("req", requestCode+"");
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
try
{
Uri audioFileUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
Log.d("uri", audioFileUri.toString());
String son[]=audioFileUri.toString().split("/");
int k=0;
int id=1;
try{
id=Integer.parseInt(son[son.length-1]);
Log.d("id", id+"");
}
catch(Exception e){
k=1;
}
Log.d("K", k+"");
if(k==0){
Uri allaudiosong = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
Uri MyUri = uri;
PreferencesClass.setUri(MyUri.toString(), getApplicationContext());
songURI=MyUri.toString();
String audioselection = MediaStore.Audio.Media.IS_MUSIC + " !=0 ";
Cursor cursor;
cursor = managedQuery(MyUri, STAR,null, null, null);
int i=0;
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
System.out.println("Audio Song Name= "+song_name);
// mysong[i]=song_name;
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
System.out.println("Audio Song ID= "+song_id);
if(id==song_id){
mysong=song_name;
if(SelectedTone.equalsIgnoreCase("Sounds")){
String[] s=mysong.split("\\.");
String rep=s[0].replace("_", " ");
if(rep.startsWith("S ")){
rep=rep.substring(2);
}
textviewRingtone.setText(UppercaseFirstLetters(rep));
}
}
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
System.out.println("Audio Song FullPath= "+fullpath);
if(id==song_id){
Log.d("Done", "Done");
//mysongPath=fullpath.substring(4, fullpath.length());
mysongPath=fullpath;
Log.d("path", fullpath);
if(SelectedTone.equalsIgnoreCase("Sounds"))
PreferencesClass.setRingtone(mysongPath, SoundActivity.this);
}
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
System.out.println("Audio Album Name= "+album_name);
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
System.out.println("Audio Album Id= "+album_id);
Log.d("Audio Album Id= ",""+album_id);
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
System.out.println("Audio Artist Name= "+artist_name);
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("Audio Artist ID= "+artist_id);
i++;
} while (cursor.moveToNext());
}
}
}
}
catch (Exception localException)
{
}
}
}
}
public void playSample(String s){
AssetFileDescriptor afd = null;
Log.d("RingtoneSelected",PreferencesClass.getRingtone(getApplicationContext()));
if(!(s.substring(0,1).equalsIgnoreCase("/"))){
try {
if(s==null){
afd = getAssets().openFd(PreferencesClass.getRingtone(getApplicationContext())+".mp3");
}else{
afd = getAssets().openFd(s+".mp3");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
player = new MediaPlayer();
try {
if(s.substring(0, 1).equalsIgnoreCase("/")){
player.setDataSource(s);
}
else
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
float volume=(float)Float.valueOf(PreferencesClass.getVolume(getApplicationContext()));
player.setVolume(volume,volume);
if(!(s.substring(0, 1).equalsIgnoreCase("/"))){
player.setLooping(true);
}
else
player.setLooping(false);
player.start();
playing=true;
if(!(s.substring(0, 1).equalsIgnoreCase("/"))){
Thread thread=new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try{
Thread.sleep(10000);
}catch(Exception e){
}
player.stop();
}
});
thread.start();
}
}
public static String UppercaseFirstLetters(String str)
{
char[] chars = str.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
I have this sound activity in which i set the ringtones according to my demand.But i want these ringtones to be beep when notifications come.I write the code for notifictaion in another activity.Can you please tell me how can i use this sound activity,so that changes made in this activity changes the notification sound??
This is my notifcation code in which code for changing the sound has to be included.Actually in this code in notification code,i have used the mobile ringtone.But i want to use the sound from custom dialog box:
Intent notificationIntent = new Intent(context, HomeTabActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, Utils.notiMsg, pendingIntent);
notification.flags|=notification.FLAG_INSISTENT|notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_LIGHTS;
//notification.vibrate=new long[] {100L, 100L, 200L, 500L};
notificationManager.notify(1, notification);
Utils.notificationReceived=true;
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(this, uri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final AudioManager audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
if(audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION)!=0){
mediaPlayer.setLooping(false);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
This is the following code which contains notification class as well as sound activity.

When do you launch your notifications from that class? On some event or...?
You can make a Service class that is used to dispatch the notifications, and whenever the user changes the notification sound you alert your Service to change the sound that will be used next time..

Related

Why I cant't get the video duration from MediaStore?

On one of my device, the following code can't make my video appear in Gallery:
File file = new File(path);
Uri uri = Uri.fromFile(file);
Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
activity.sendBroadcast(scanFileIntent);
So I use scanFile explicitly:
android.media.MediaScannerConnection.scanFile(activity, new String[]{file.getAbsolutePath()},
new String[]{"video/" + mMimeType}, null);
When my video is xxx.mpeg4, the value of mMimeType is mp4, the result is that the video can appear in MediaStore but I can't get the duration later(the returned value is always 0). Need help on this.
public static long[] getVideoDetail(Context context, Uri uri) {
long[] result = new long[] {DEFAULT_VIDEO_FRAME_WIDTH, DEFAULT_VIDEO_FRAME_HEIGHT, -1};
if(uri == null || (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()))) {
return result;
}
String[] projection = new String[] {MediaStore.Video.Media.RESOLUTION, MediaStore.Video.VideoColumns.DURATION};
Cursor cursor = null;
boolean success = false;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor.moveToFirst()) {
String resolution = cursor.getString(0);
if(!StringUtils.isEmpty(resolution)) {
int index = resolution.indexOf('x');
result[0] = Integer.parseInt(resolution.substring(0, index));
result[1] = Integer.parseInt(resolution.substring(index + 1));
if(result[0] != 0 && result[1] != 0) {
success = true;
}
if(result[0] > result[1]) {
swap(result, 0, 1);
}
}
result[2] = cursor.getLong(1);
if(result[2] >= 0 && success) {
success = true;
} else {
success = false;
}
}
if (null != cursor) {
cursor.close();
}
}
catch (Exception e) {
// do nothing
} finally {
try {
if (null != cursor) {
cursor.close();
}
} catch (Exception e2) {
// do nothing
}
}
if (!success) {
try {
ContentResolver contentResolver = context.getContentResolver();
String selection = MediaStore.Images.Media._ID + "= ?";
String id = uri.getLastPathSegment();
String[] selectionArgs = new String[]{ id };
cursor = contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, null);
if (cursor.moveToFirst()) {
String resolution = cursor.getString(0);
if(!StringUtils.isEmpty(resolution)) {
int index = resolution.indexOf('x');
result[0] = Integer.parseInt(resolution.substring(0, index));
result[1] = Integer.parseInt(resolution.substring(index + 1));
if(result[0] > result[1]) {
swap(result, 0, 1);
}
}
result[2] = cursor.getLong(1);
}
if (null != cursor) {
cursor.close();
}
} catch (Exception e) {
// do nothing
} finally {
try {
if (cursor != null) {
cursor.close();
}
} catch (Exception e) {
// do nothing
}
}
}
if(result[0] <= 0) {
result[0] = DEFAULT_VIDEO_FRAME_WIDTH;
}
if(result[1] <= 0) {
result[1] = DEFAULT_VIDEO_FRAME_HEIGHT;
}
return result;
}
As I see in your code you are requesting duration in your projection
String[] projection = new String[] {MediaStore.Video.Media.RESOLUTION, MediaStore.Video.VideoColumns.DURATION};
now you just need to retrieve it from the cursor like shown below:
long timeInMs = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION));
get help from MediaPlayer :
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(context, Uri.parse(uri));
} catch (IOException e) {
Log.d("-MS-","Cannot parse url");
e.printStackTrace();
}
int duration= mp.getDuration();
String[] projection = new String[] {MediaStore.Video.Media.RESOLUTION,duration};
I always get Duration by MediaPlayer.

How can I separate incoming and outgoing call recorded files in listview in android

I am developing recording application. In that it will record all incoming and outgoing calls and am displayed these calls in ListView. I want to display separate symbols for incoming and outgoing recording files. How can I separate it? Please provide solution. If possible provide source code.
Thank you.
CallBroadCastReceiver.java
public class CallBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.d("CallRecorder", "CallBroadcastReceiver:onReceive got Intent: " + intent.toString());
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
String numberToCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.d("CallRecorder", "CallBroadcastReceiver intent has EXTRA_PHONE_NUMBER: " + numberToCall);
}
PhoneListener phoneListener = new PhoneListener(context);
TelephonyManager telephony = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Log.d("PhoneStateReceiver:onReceive", "set PhoneStateListener");
}
}
PhoneListener.java
public class PhoneListener extends PhoneStateListener {
private Context context;
public PhoneListener(Context c) {
Log.i("CallRecorder", "PhoneListener constructor");
context = c;
}
public void onCallStateChanged(int state, String incomingNumber) {
Log.d("CallRecorder", "PhoneListener::onCallStateChanged state:" + state + " incomingNumber:" + incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d("CallRecorder", "CALL_STATE_IDLE, stoping recording");
Boolean stopped = context.stopService(new Intent(context, RecordService.class));
Log.i("CallRecorder", "stopService for RecordService returned " + stopped);
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d("CallRecorder", "CALL_STATE_RINGING");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d("CallRecorder", "CALL_STATE_OFFHOOK starting recording");
Intent callIntent = new Intent(context, RecordService.class);
ComponentName name = context.startService(callIntent);
if (null == name) {
Log.e("CallRecorder", "startService for RecordService returned null ComponentName");
} else {
Log.i("CallRecorder", "startService returned " + name.flattenToString());
}
break;
}
}
}
CallLog.java
public class CallLoglist extends Activity {
private final String TAG = "CallRecorder";
private ListView fileList = null;
//public static ArrayAdapter<String> fAdapter = null;
private SeekBar seekbar;
private MediaPlayer mediaPlayer = new MediaPlayer();
public static ImageButton pauseButton;
public TextView startTimeField, endTimeField;
AudioManager audioManager;
public static final String STORAGE_LOCATIONN = Environment.getExternalStorageDirectory() + "/Android/data/com.callrecorder/favourites";
Handler seekHandler = new Handler();
Dialog seekDialog;
private Utilities utils;
long totalDuration, currentDuration;
public static ImageView img;
String[] dlist;
String recordlist;
private list fAdapter;
ArrayList<String> alist;
Cursor managedCursor;
StringBuffer sb;
public String name;
public String number;
File source;
CallLoglist cc;
public static boolean ss;
String phNumber;
public static int a;
public static Editor ed;
public static SharedPreferences pref;
public static ArrayList<Boolean> arr = new ArrayList<Boolean>();
private class CallItemClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.showContextMenu();
CharSequence s = (CharSequence) parent.getItemAtPosition(position);
Log.w(TAG, "CallLog just got an item clicked: " + s);
//File f = new File(RecordService.DEFAULT_STORAGE_LOCATION + "/" + s.toString());
/*boolean useMediaController = true;
if (useMediaController) {
Intent playIntent = new Intent(getApplicationContext(), CallPlayer.class); //Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(f);
playIntent.setData(uri);
startActivity(playIntent);
} else {
playFile(s.toString());
}*/
}
}
#SuppressLint("ShowToast")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
setContentView(R.layout.call_log);
fileList = (ListView) findViewById(R.id.play_file_list);
img = (ImageView) findViewById(R.id.image);
Context context = getApplicationContext();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
utils = new Utilities();
File dir = new File(RecordService.LOCATION);
dlist = dir.list();
alist = new ArrayList<String>(Arrays.asList(dlist));
Log.v("fille", "recording file" + recordlist);
fAdapter = new list(this, alist);
fileList.setAdapter(fAdapter);
fileList.setOnItemClickListener(new CallItemClickListener());
registerForContextMenu(fileList);
pref = getSharedPreferences("mm", MODE_PRIVATE);
ed = pref.edit();
/* ed.putString("rr", "R.drawable.arrow");
ed.putString("re", "R.drawable.arroww");*/
ed.commit();
////////////////
/*String[] projection = new String[] {android.provider.CallLog.Calls.NUMBER, android.provider.CallLog.Calls.DATE, android.provider.CallLog.Calls.CACHED_NAME};
Uri contacts = android.provider.CallLog.Calls.CONTENT_URI;
Cursor managedCursor = managedQuery(contacts, projection, null, null, android.provider.CallLog.Calls.DATE + " ASC");
getColumnData(managedCursor);
}
private void getColumnData(Cursor cur){
try{
if (cur.moveToFirst()) {
long date;
int nameColumn = cur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
int numberColumn = cur.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int dateColumn = cur.getColumnIndex(android.provider.CallLog.Calls.DATE);
System.out.println("Reading Call Details: ");
do {
name = cur.getString(nameColumn);
number = cur.getString(numberColumn);
date = cur.getLong(dateColumn);
System.out.println(number + ":"+ new Date(date) +":"+name);
} while (cur.moveToNext());
}
}
finally{
cur.close();
}*/
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater m = getMenuInflater();
m.inflate(R.menu.nn, menu);
}
#SuppressLint({"ShowToast", "SdCardPath"})
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;
recordlist = alist.get(index);
//pp=dlist.
switch (item.getItemId()) {
case R.id.play:
seekDialog = new Dialog(this);
seekDialog.setTitle("play");
seekDialog.setContentView(R.layout.dialog);
startTimeField = (TextView) seekDialog.findViewById(R.id.textView1);
endTimeField = (TextView) seekDialog.findViewById(R.id.textView2);
pauseButton = (ImageButton) seekDialog.findViewById(R.id.imageButton2);
seekbar = (SeekBar) seekDialog.findViewById(R.id.seek);
seekDialog.show();
Log.v("file", "" + index);
if (mediaPlayer != null) {
mediaPlayer.release();
}
/*mediaPlayer=MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/Android/data/com.callrecorder/recordings/" +pathh ));*/
mediaPlayer = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/Android/data/com.callrecorder/recordings/" + recordlist));
mediaPlayer.start();
seekUpdation();
totalDuration = mediaPlayer.getDuration();
seekbar.setMax((int) totalDuration);
pauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
pauseButton.setImageResource(R.drawable.play);
Toast.makeText(getApplicationContext(), "pause", 1000).show();
} else {
mediaPlayer.start();
pauseButton.setImageResource(R.drawable.pause);
Toast.makeText(getApplicationContext(), "play", 1000).show();
}
}
});
seekDialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
mediaPlayer.release();
}
});
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mediaPlayer.pause();
seekbar.setProgress(mediaPlayer.getCurrentPosition());
seekbar.setMax(mediaPlayer.getDuration());
mediaPlayer.seekTo(progress);
mediaPlayer.start();
pauseButton.setImageResource(R.drawable.pause);
seekUpdation();
}
}
});
break;
case R.id.delete:
Toast.makeText(getApplicationContext(), "delete", 1000).show();
//new File(Environment.getExternalStorageDirectory()+"/callrecorder/" + pathh).delete();
new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.callrecorder/recordings/" + recordlist).delete();
alist.remove(index);
alist.clear();
fAdapter.notifyDataSetChanged();
fAdapter.notifyDataSetInvalidated();
break;
case R.id.favorites:
Toast.makeText(getApplicationContext(), "favouraties", 1000).show();
source = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.callrecorder/recordings/" + recordlist);
File dir = new File(STORAGE_LOCATIONN);
if (!dir.exists()) {
try {
dir.mkdir();
} catch (Exception e) {
// TODO: handle exception
}
}
try {
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(STORAGE_LOCATIONN + "/" + recordlist);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (Exception e) {
// TODO: handle exception
Log.v("copyyy", "errorrrrr");
}
source.delete();
alist.remove(index);
fAdapter.notifyDataSetChanged();
fAdapter.notifyDataSetInvalidated();
break;
default:
}
return super.onContextItemSelected(item);
}
Runnable runn = new Runnable() {
#Override
public void run() {
try {
seekUpdation();
} catch (Exception e) {
// TODO: handle exception
}
try {
totalDuration = mediaPlayer.getDuration();
currentDuration = mediaPlayer.getCurrentPosition();
// Displaying Total Duration time
endTimeField.setText("" + utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
startTimeField.setText("" + utils.milliSecondsToTimer(currentDuration));
seekbar.setProgress((int) currentDuration); //move seek bar
// Updating progress bar
/* int progress = (int)(utils.getProgressPercentage(currentDuration,totalDuration));
//Log.d("Progress", ""+progress);
seekbar.setProgress(progress);*/
// seekHandler.postDelayed(this, 100);
} catch (Exception e) {
// TODO: handle exception
}
}
};
public void seekUpdation() {
//seekbar.setProgress(mediaPlayer.getCurrentPosition());
//mHandler.postDelayed(mUpdateTimeTask, 100);
seekHandler.postDelayed(runn, 1000);
}
public void onStart() {
super.onStart();
Log.i(TAG, "CallLog onStart");
}
public void onRestart() {
super.onRestart();
Log.i(TAG, "CallLog onRestart");
}
/*public void onResume()
{
super.onResume();
//Log.i(TAG, "CallLog onResume about to load recording list again, does this work?");
loadRecordingsFromDir();
}*/
#Override
protected void onDestroy() {
/*if(null!=mediaPlayer){
mediaPlayer.release();
}*/
super.onDestroy();
if (mediaPlayer != null) {
//mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
///////////////////////////////////////////
private class list extends BaseAdapter {
private CallLoglist callLog;
private ArrayList<String> alist;
public list(CallLoglist callLog, ArrayList<String> alist) {
// TODO Auto-generated constructor stub
this.callLog = callLog;
this.alist = alist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return alist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.calllist, parent, false);
TextView textView = (TextView) v.findViewById(R.id.text);
ImageView imageView = (ImageView) v.findViewById(R.id.image);
textView.setText(alist.get(position));
String aa = pref.getString("rr", "");
String dd = pref.getString("re", "");
if (aa.equals("0")) {
imageView.setImageResource(R.drawable.arrow);
} else {
imageView.setImageResource(R.drawable.arroww);
}
//imageView.setImageResource(R.drawable.arrow);
//TextView text=(TextView)v.findViewById(R.id.namee);
/*if(arr.get(position))
{
imageView.setImageResource(R.drawable.arrow);
}
else {
imageView.setImageResource(R.drawable.arroww);
}*/
return v;
}
}
}
Recordservice.java
public class RecordService
extends Service
implements MediaRecorder.OnInfoListener, MediaRecorder.OnErrorListener {
private static final String TAG = "CallRecorder";
//public static final String DEFAULT_STORAGE_LOCATION = "/sdcard/callrecorder";
public static final String DEFAULT_STORAGE_LOCATION = "/sdcard/Android/data/com.callrecorder/recordings";
private static final int RECORDING_NOTIFICATION_ID = 1;
private MediaRecorder recorder = null;
private boolean isRecording = false;
private String incoming;
private Toast size;
public static File recording = null;
;
Intent intent;
private File makeOutputFile(SharedPreferences prefs) {
File dir = new File(DEFAULT_STORAGE_LOCATION);
// test dir for existence and writeability
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
Log.e("CallRecorder", "RecordService:makeOutputFile unable to create directory " + dir + ": " + e);
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to create the directory " + dir + " to store recordings: " + e, Toast.LENGTH_LONG);
t.show();
return null;
}
} else {
if (!dir.canWrite()) {
Log.e(TAG, "RecordService:makeOutputFile does not have write permission for directory: " + dir);
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder does not have write permission for the directory directory " + dir + " to store recordings", Toast.LENGTH_LONG);
t.show();
return null;
}
}
String prefix = "cal";
//String prefix= PhoneListener.incoming;
int audiosource = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1"));
//prefix += "-" + audiosource ;
prefix += "" + PhoneListener.incoming;
String suffix = "";
int audioformat = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_FORMAT, "1"));
switch (audioformat) {
case MediaRecorder.OutputFormat.THREE_GPP:
suffix = ".3gpp";
break;
case MediaRecorder.OutputFormat.MPEG_4:
suffix = ".mpg";
break;
case MediaRecorder.OutputFormat.RAW_AMR:
suffix = ".amr";
break;
}
try {
return File.createTempFile(prefix, suffix, dir);
} catch (IOException e) {
Log.e("CallRecorder", "RecordService:makeOutputFile unable to create temp file in " + dir + ": " + e);
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to create temp file in " + dir + ": " + e, Toast.LENGTH_LONG);
t.show();
return null;
}
}
public void onCreate() {
super.onCreate();
recorder = new MediaRecorder();
Log.i("CallRecorder", "onCreate created MediaRecorder object");
}
#SuppressLint("ShowToast")
public void onStart(Intent intent, int startId) {
Log.i("CallRecorder", "RecordService:onStartCommand called while isRecording:" + isRecording);
if (isRecording) return;
Context c = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
Boolean shouldRecord = prefs.getBoolean(Preferences.PREF_RECORD_CALLS, false);
if (!shouldRecord) {
Log.i("CallRecord", "RecordService:onStartCommand with PREF_RECORD_CALLS false, not recording");
return;
}
int audiosource = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1"));
int audioformat = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_FORMAT, "1"));
recording = makeOutputFile(prefs);
if (recording == null) {
recorder = null;
return; //return 0;
}
Log.i("CallRecorder", "RecordService will config MediaRecorder with audiosource: " + audiosource + " audioformat: " + audioformat);
try {
recorder.reset();
recorder.setAudioSource(audiosource);
Log.d("CallRecorder", "set audiosource " + audiosource);
recorder.setOutputFormat(audioformat);
Log.d("CallRecorder", "set output " + audioformat);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
Log.d("CallRecorder", "set encoder default");
recorder.setOutputFile(recording.getAbsolutePath());
Log.d("CallRecorder", "set file:" + recording);
recorder.setOnInfoListener(this);
recorder.setOnErrorListener(this);
try {
recorder.prepare();
} catch (java.io.IOException e) {
Log.e("CallRecorder", "RecordService:onStart() IOException attempting recorder.prepare()\n");
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to start recording: " + e, Toast.LENGTH_LONG);
t.show();
recorder = null;
return; //return 0; //START_STICKY;
}
Log.d("CallRecorder", "recorder.prepare() returned");
recorder.start();
isRecording = true;
Log.i("CallRecorder", "recorder.start() returned");
updateNotification(true);
} catch (java.lang.Exception e) {
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to start recording: " + e, Toast.LENGTH_LONG);
t.show();
Log.e("CallRecorder", "RecordService:onStart caught unexpected exception", e);
recorder = null;
}
return;
}
public void onDestroy() {
super.onDestroy();
if (null != recorder) {
Log.i("CallRecorder", "RecordService:onDestroy calling recorder.release()");
isRecording = false;
recorder.release();
long length = recording.length();
length = length / 1024;
Log.v("call", "pathh" + recording.getAbsolutePath() + length + "KB");
if (length == 0) {
Log.v("sizeeee", "settings");
Toast.makeText(getApplicationContext(), "change the audio source settings", Toast.LENGTH_LONG).show();
recording.delete();
Log.v("file", "delete");
}
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder finished recording call to" + recording, Toast.LENGTH_LONG);
t.show();
}
updateNotification(false);
}
// methods to handle binding the service
public IBinder onBind(Intent intent) {
return null;
}
public boolean onUnbind(Intent intent) {
return false;
}
public void onRebind(Intent intent) {
}
private void updateNotification(Boolean status) {
Context c = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
if (status) {
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Recording call " + prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1");
//CharSequence tickerText = "Recording call " + prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1");
long when = System.currentTimeMillis();
//Notification notification = new Notification(icon, tickerText, when);
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "CallRecorder Status";
CharSequence contentText = "Recording call...";
Intent notificationIntent = new Intent(this, RecordService.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(RECORDING_NOTIFICATION_ID, notification);
} else {
mNotificationManager.cancel(RECORDING_NOTIFICATION_ID);
}
}
// MediaRecorder.OnInfoListener
public void onInfo(MediaRecorder mr, int what, int extra) {
Log.i("CallRecorder", "RecordService got MediaRecorder onInfo callback with what: " + what + " extra: " + extra);
isRecording = false;
}
// MediaRecorder.OnErrorListener
public void onError(MediaRecorder mr, int what, int extra) {
Log.e("CallRecorder", "RecordService got MediaRecorder onError callback with what: " + what + " extra: " + extra);
isRecording = false;
mr.release();
}
}
You would have to create a a broadcastreceiver. The receiver detects if an call is incoming or outgoing. There you can record your calls. Use TelephonyManager Class. And add permissions in the manifest.
In the link is a basic description with source-code download:
http://www.devlper.com/2010/08/detecting-incoming-and-outgoing-calls-in-android/
If you get that working, you just would have to create a Dictionary(HashMap). There you could set the dictionary-key to save numbers and a key-value for incoming or outgoing calls.
Get familiar with custom ListView to create a ListView with an image.
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
Create 2 images, incoming and outgoing. Lopp through your dictionary and set the images right.
Greets

cant find audiofile when recording sound

My Problem is, that I capture audio by pressing the record button, but I can't see any audioFile in the specific path.
I capture sound, when I press the capture button:
private void startRecord()
{
ImageButton soundStop = (ImageButton)findViewById(R.id.soundstop);
soundStop.setVisibility(View.VISIBLE);
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//mediaRecorder.setOutputFormat(sound);
//mediaRecorder.setOutputFile(soundFilePath);
//mediaRecorder.setAudioEncoder(audioEncoder);
//Log.d("hier ", "hier" + soundFilePath);
try {
mediaRecorder.prepare();
mediaRecorder.start();
}catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Aufnahme gestartet", Toast.LENGTH_LONG).show();
}
When I press the Stop Recording Button the file should be saved in the specific path. I tried it with Directory Musik and Downloads, but I can't find any file there
final OnClickListener soundRecordStop = new OnClickListener(){
#Override
public void onClick(View v) {
soundStop();
}
};
public void soundStop(){
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
Timestamp time = new Timestamp(System.currentTimeMillis());
String actualTime = sdf.format(time);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = sharedPreferences.getString("soundformat", "format");
int audioEncoder = sharedPreferences.getInt("audioEncoder", Property.getAudioEncoderInt());
String dateiendung = ".aac";
int sound = 6;
if(name == "aac"){
dateiendung = ".aac";
sound = 6;
} else if(name == "amr_nb"){
dateiendung = ".3gp";
sound = 3;
}
else if( name == "amr_wb"){
dateiendung = ".3gp";
sound = 4;
}
else if( name == "default" ){
dateiendung = ".default";
sound = 0;
}
else if( name == "mpeg"){
dateiendung = ".mp4";
sound = 2;
}
else if( name == "gpp" ){
Log.d("in gpp", "in gpp");
dateiendung = ".3gp";
sound = 1;
}
soundFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
soundFilePath = soundFile.getAbsolutePath() + actualTime + dateiendung;
Log.d("hier ", "hier1" + mediaRecorder);
if(mediaRecorder != null){
Log.d("hier ", "hier2" + mediaRecorder);
try {
//mediaRecorder.prepare();
mediaRecorder.stop();
mediaRecorder.release();
//mediaRecorder = null;
Log.d("hier ", "hier4" + mediaRecorder);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mediaRecorder.setOutputFormat(sound);
mediaRecorder.setOutputFile(soundFilePath);
Log.d("hier ", "hier2");
String pfad = soundFile.getAbsolutePath();
Toast.makeText(getApplicationContext(), "Aufnahme in " + pfad + " gespeichert", Toast.LENGTH_LONG).show();
ImageButton soundStop = (ImageButton)findViewById(R.id.soundstop);
soundStop.setVisibility(View.INVISIBLE);
}
The path seems to be correct: pfad /storage/sdcard0/Download17.07.2014 11:55:58.aac
Thanks for the comment the missing File Separator wasn't intentionally. I insert the missing Separator in Order to save the audio File in Downloads Directory. But no File nevertheless 😑
Please help me to find my file ;)

java - Android HttpPost Black Screen while sending files to server

I am sending images and audio files to my php server. I am using Asynctask for this. I have two activities in my program. The problem is if I launch my second activity (AudioActivity) from MainActivity like this
upload_audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AudioActivity.class);
startActivity(intent);
}
});
then when i click the button upload_audio the screen goes black but the process still running successfully . so if i make this audio activity my mainActivity then everything works perfect.so how can i make my app still visible during processing files while launching activity from MainActivity.hope you understand my question
here is my code of AudioActivity
public class AudioActivity extends Activity {
private static final int SELECT_AUDIO = 2;
String selectedPath = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upload();
}
public void upload() {
ArrayList<Uri> fileName = getFileList(this);
for ( int i = 0 ; i < fileName.size() ; i++ )
{
try {
selectedPath = getPath(fileName.get(i)).toString();
System.out.println(getPath(fileName.get(i)));
new AudioSync(selectedPath).execute(getPath(fileName.get(i))).get();
// AudioSync sync = new AudioSync(getPath(fileName.get(i))).get;
//new AudioSync().execute("").get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Audio.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private ArrayList<Uri> getFileList(Context context) {
Cursor actualimagecursor = null;
ArrayList<Uri> fileList = new ArrayList<Uri>();
try
{
String[] proj = { MediaStore.Audio.Media.DATA, MediaStore.Audio.Media._ID };
actualimagecursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj,
null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
for ( int i = 0 ; i < actualimagecursor.getCount() ; i++ )
{
actualimagecursor.moveToPosition(i);
String fileName = actualimagecursor.getString(actual_image_column_index);
fileList.add(( Uri.withAppendedPath( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, fileName )));
}
return fileList;
}
catch ( Exception e )
{
return null;
}
}
}
You don't want to create an Activity for uploading or playing Audio. Activities are always linked with views and are use to interact with the user.
http://developer.android.com/guide/components/activities.html
You want to use a service to do that: http://developer.android.com/guide/components/services.html

Download Manager failed the download

I am using DownloadManager to download the following url:
http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
But the downloading is failed. I even hit the url on browser and it works properly. Is it the problem of url parsing?
Code: DDownloadService.java
public class DDownloadService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
Context conte;
// NotificationManager notificationManager;
// NotificationCompat.Builder mBuilder;
boolean playing = false;
Runnable runnable;
SharedPreferences pre;
static int countOfCurrent = 0;
String downloadName, downloadUrl;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
// ..
static int downloadNumber = 0;
DownloadManager mgr[] = new DownloadManager[100];
long downloadIds[] = new long[100];
BroadcastReceiver cancelDownload;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
downloadNumber++;
downloadName = pre.getString("downloadname", "");
downloadName = viewSD(downloadName);
downloadUrl = pre.getString("downloadurl", "");
downloadName = downloadName.toLowerCase();
pre.edit()
.putString(
"songsInDownload",
pre.getString("songsInDownload", "") + "|"
+ downloadName).commit();
pre.edit().putInt(downloadName + "no", +downloadNumber).commit();
mgr[downloadNumber] = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
try {
countOfCurrent++;
downloadIds[downloadNumber] = mgr[downloadNumber]
.enqueue(new DownloadManager.Request(Uri
.parse(downloadUrl))
.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("Downloading")
.setDescription(downloadName)
.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_HIDDEN)
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_MUSIC,
downloadName)
.setVisibleInDownloadsUi(false));
pre.edit()
.putLong(downloadName + "id",
downloadIds[downloadNumber]).commit();
Timer myTimer = new Timer();
myTimer.schedule(new RegrowCornAnimate(downloadNumber,
downloadName), 0, 10);
} catch (IllegalStateException e) {
Toast.makeText(getBaseContext(), "No storage found!",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(getBaseContext(), " Something wrong happened!",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
#Override
public void onCreate() {
conte = this;
pre = getSharedPreferences("download", 0);
downloadName = pre.getString("downloadname", "");
downloadUrl = pre.getString("downloadurl", "");
cancelDownload = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
try {
mgr[pre.getInt(arg1.getExtras().getString("name") + "no", 0)]
.remove(pre.getLong(
arg1.getExtras().getString("name") + "id",
0));
} catch (Exception e) {
e.printStackTrace();
}
}
};
registerReceiver(cancelDownload, new IntentFilter("cancelIt"));
notificationManager = (NotificationManager) conte
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Downloading in progress").setContentText("");
startForeground(55, mBuilder.build());
notificationManager.cancel(55);
HandlerThread thread = new HandlerThread("ServiceStartArguments", 0);
// //..................
// notificationManager = (NotificationManager) conte
// .getSystemService(Context.NOTIFICATION_SERVICE);
// mBuilder = new NotificationCompat.Builder(conte);
// RemoteViews remoteViews = new RemoteViews(getPackageName(),
// R.layout.notification_layout);
// try {
// mBuilder.setSmallIcon(R.drawable.icon);
// mBuilder.setAutoCancel(false).setOngoing(true)
// .setContent(remoteViews);
// Uri uri = RingtoneManager
// .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// mBuilder.setSound(uri);
// notificationManager.notify(Mp3Constants.NOTIFICATION_NUMBER,
// mBuilder.build());
// } catch (Exception e) {
// e.printStackTrace();
// }
// //...................
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// online = intent.getExtras().getString("online");
// link = intent.getExtras().getString("link");
// name = intent.getExtras().getString("name");
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(cancelDownload);
}
class RegrowCornAnimate extends TimerTask {
private final int serial;
private final String name_of_da;
boolean startFlag = true, errorFlag = true;
RegrowCornAnimate(int serial, String name) {
this.serial = serial;
this.name_of_da = name;
}
public void run() {
// Do stuff
int dl_progress = 0;
try {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadIds[serial]);
Cursor c = mgr[serial].query(q);
c.moveToFirst();
long bytes_downloaded = c
.getInt(c
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
long bytes_total = c
.getInt(c
.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
dl_progress = (int) ((bytes_downloaded * 100) / bytes_total);
pre.edit().putInt(name_of_da, dl_progress).commit();
switch (c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
case DownloadManager.STATUS_FAILED:
// msg = "Download failed!";
// Toast.makeText(getBaseContext(), "Url Broken!",
// Toast.LENGTH_SHORT).show();
sendNotification(1, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
case DownloadManager.STATUS_PAUSED:
// msg = "Download paused!";
if (errorFlag) {
errorFlag = false;
sendNotification(7, serial, name_of_da, dl_progress);
}
break;
case DownloadManager.STATUS_PENDING:
// msg = "Download pending!";
sendNotification(0, serial, name_of_da, dl_progress);
break;
case DownloadManager.STATUS_RUNNING:
// msg = "Download in progress!";
errorFlag = true;
if (startFlag) {
if (verifyFromSD(name_of_da)) {
startFlag = false;
sendBroadcast(new Intent("start"));
}
}
sendNotification(0, serial, name_of_da, dl_progress);
break;
case DownloadManager.STATUS_SUCCESSFUL:
// msg = "Download complete!";
pre.edit()
.putString(
"songsInDownload",
pre.getString("songsInDownload", "")
.replace("|" + name_of_da, ""))
.commit();
pre.edit().putInt(name_of_da, 100);
sendNotification(0, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
default:
// msg = "Download is nowhere in sight";
sendNotification(10, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
}
c.close();
} catch (Exception e) {
e.printStackTrace();
sendNotification(7, serial, name_of_da, dl_progress);
cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
}
}
}
public void sendNotification(int tmout, int nin, String name, int progress) {
if (tmout == 0) {
// notificationManager.notify(nin, mBuilder.build());
if (progress >= 100) {
// notificationManager.cancel(nin);
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Completed").setContentText(name)
.setAutoCancel(true).setOngoing(false)
.setProgress(100, 100, false);
Uri ttt = Uri.parse(Environment.getExternalStorageDirectory()
.toString() + "/Music/" + name);
pre.edit().putInt("retry", 1).commit();
Intent inten = new Intent(Intent.ACTION_VIEW, ttt);
String arr[] = name.split("\\.");
inten.setDataAndType(ttt, "audio/" + arr[arr.length - 1]);
PendingIntent i = PendingIntent.getActivity(getBaseContext(),
0, inten, 0);
mBuilder.setContentIntent(i);
notificationManager.notify(nin, mBuilder.build());
} else {
mBuilder.setContentTitle("Downloading: " + name)
.setContentText(progress + " %")
.setSmallIcon(R.drawable.icon).setAutoCancel(false)
.setOngoing(true);
mBuilder.setProgress(100, progress, false);
notificationManager.notify(nin, mBuilder.build());
}
} else {
if (tmout == 1) {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Failed: " + name)
.setContentText(progress + " %").setAutoCancel(true)
.setProgress(100, progress, false).setOngoing(false);
// Intent intnt = new Intent(Mp3Constants.NOTIFICATION);
// intnt.putExtra("resume", "1");
// intnt.putExtra("url", urlD);
// intnt.putExtra("name", name);
// intnt.putExtra("nin", nin);
// PendingIntent i = PendingIntent
// .getBroadcast(conte, 0, intnt, 0);
// mBuilder.setContentIntent(i);
} else if (tmout == 7) {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Cancelled: " + name)
.setAutoCancel(true).setProgress(100, progress, false)
.setOngoing(false);
// Intent intnt = new Intent(Mp3Constants.NOTIFICATION);
// intnt.putExtra("resume", "1");
// intnt.putExtra("url", urlD);
// intnt.putExtra("name", name);
// intnt.putExtra("nin", nin);
// PendingIntent i = PendingIntent
// .getBroadcast(conte, 0, intnt, 0);
// mBuilder.setContentIntent(i);
} else {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Interrupted: " + name)
.setContentText("No storage found").setAutoCancel(true)
.setOngoing(false);
}
notificationManager.notify(nin, mBuilder.build());
}
}
private String viewSD(String naame) {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return naame;
}
while (true) {
String newName = naame;
naame = relooper(files, newName);
if (newName.equals(naame))
break;
}
return naame;
}
public String relooper(File[] files, String name) {
int send = files.length;
for (int i = 0; i < send; i++) {
File file = files[i];
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
if (name.equalsIgnoreCase(myfile))
return "copy_of_" + name;
}
return name;
}
private boolean verifyFromSD(String naame) {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return false;
}
int send = files.length;
for (int i = 0; i < send; i++) {
File file = files[i];
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
if (naame.equalsIgnoreCase(myfile))
return true;
}
return false;
}
}
EDIT: I found the problem from logcat:
01-07 11:47:37.313: W/DownloadManager(18893): Exception for id 285: Illegal character in path at index 115: http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
01-07 11:47:37.313: W/DownloadManager(18893): java.lang.IllegalArgumentException: Illegal character in path at index 115: http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
01-07 11:47:37.313: W/DownloadManager(18893): at java.net.URI.create(URI.java:727)
01-07 11:47:37.313: W/DownloadManager(18893): at android.net.Proxy.getProxy(Proxy.java:113)
01-07 11:47:37.313: W/DownloadManager(18893): at android.net.Proxy.getPreferredHttpHost(Proxy.java:218)
01-07 11:47:37.313: W/DownloadManager(18893): at com.android.providers.downloads.DownloadThread.run(DownloadThread.java:174)
But I still need to know which format to use to parse url for DownloadManager.
The IllegalArgumentException occurs when the URL contains illegal characters such as [ ]. As mentioned in the comments, you need to encode such characters using URLEncoder.
I implemented it this way in my code -
private String checkUrl(String url) {
if(url.contains("[")) {
String[] a = url.split("\\[");
String b = "[" + a[1]; //contains text after [ e.g. [DJKANG.Com].mp3
url = a[0] + URLEncoder.encode(b, "UTF-8"); // encodes illegal characters
}
return url;
}

Categories

Resources