Related
I have question about saving audio/mp3
file to external storage
after saving the file it show in external storage
but when I open any android music player the file not showing there
I try to change the folder to "/storage/emulated/0/Music/" still not showing
even on download folder nothing.
the app is for download music from YouTube using API
public class DownloadedActivity extends AppCompatActivity implements AdapterMusicDownloaded.ClickCallBack, View.OnClickListener {
private RecyclerView lvManager;
private AdapterMusicDownloaded adapterMusicSearch;
private ArrayList<ItemMusicDownloaded> arrayList = new ArrayList<>();
private LinearLayout llEmptyFile;
private static final String AUTHORITY = "com.free.music.downloader" + ".fileprovider";
public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/FreeMusic/";
public static final String UPDATE_MUSIC = "update_music";
private ImageView imgBackSearch;
private InterstitialAd mInterstitialAd;
private AdView adView;
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_downloaded_songs);
initViews();
}
private void initViews() {
loading = findViewById(R.id.loading);
adView = findViewById(R.id.adView);
initAdsFull();
MobileAds.initialize(this, getResources().getString(R.string.mobile_id));
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
llEmptyFile = findViewById(R.id.ll_empty_file);
imgBackSearch = findViewById(R.id.img_back_downloaded);
imgBackSearch.setOnClickListener(this);
lvManager = findViewById(R.id.lv_main);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
adapterMusicSearch = new AdapterMusicDownloaded(arrayList, this);
adapterMusicSearch.setCallBack(this);
lvManager.setLayoutManager(manager);
lvManager.setAdapter(adapterMusicSearch);
LoadAsync loadAsync = new LoadAsync();
loadAsync.execute();
}
#Override
public void clickItemMusic(int position) {
Intent playIntent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
final File photoFile = new File(arrayList.get(position).getLink());
Uri photoURI = FileProvider.getUriForFile(this, AUTHORITY, photoFile);
playIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
playIntent.setDataAndType(photoURI, "audio/*");
} else {
playIntent.setDataAndType(Uri.parse(arrayList.get(position).getLink()), "audio/*");
}
startActivity(playIntent);
}
#Override
public void clickOptionItemMusic(final int postion, View view) {
PopupMenu popupMenu = new PopupMenu(this, view);
popupMenu.inflate(R.menu.menu_option_main);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
File file = new File(arrayList.get(postion).getLink());
boolean deleted = file.delete();
if (deleted) {
Toast.makeText(DownloadedActivity.this, getResources().getString(R.string.delete_finish), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DownloadedActivity.this, getResources().getString(R.string.delete_error), Toast.LENGTH_SHORT).show();
}
arrayList.remove(postion);
adapterMusicSearch.notifyDataSetChanged();
break;
case R.id.menu_share_main:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
final File photoFile = new File(arrayList.get(postion).getLink());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri photoURI = FileProvider.getUriForFile(DownloadedActivity.this, AUTHORITY, photoFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
} else {
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
}
shareIntent.setType("audio/*");
startActivity(Intent.createChooser(shareIntent, "Share music"));
break;
default:
break;
}
return false;
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.img_back_downloaded) {
onBackPressed();
}
}
#Override
public void onBackPressed() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
finish();
}
}
private class LoadAsync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
llEmptyFile.setVisibility(View.GONE);
loading.setVisibility(View.VISIBLE);
}
#SuppressLint("WrongThread")
#Override
protected String doInBackground(Void... voids) {
arrayList.clear();
File f = new File(PATH);
File[] files = f.listFiles();
if (f.exists()) {
if (files.length <= 0) {
Log.d("sizearrList", "0");
return "OK";
} else {
Log.d("sizearrList", "2");
arrayList.clear();
Arrays.sort(files, new Comparator() {
public int compare(Object o1, Object o2) {
if (((File) o1).lastModified() > ((File) o2).lastModified()) {
return -1;
} else if (((File) o1).lastModified() < ((File) o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
for (File aFile : files) {
if (!aFile.isDirectory()) {
String name = aFile.getName();
String path = aFile.getPath();
getTimeVideo(aFile.getAbsolutePath());
Date lastModified = getFileLastModified(path);
arrayList.add(new ItemMusicDownloaded(name, path, lastModified, getTimeVideo(aFile.getAbsolutePath())))
;
} else {
Log.d("myLog", "Do not add");
}
}
Log.d("sizeArrsss", arrayList.size() + "");
for (int i = 0; i < arrayList.size(); i++) {
Log.d("sizeArr", arrayList.get(i).getTitle());
}
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (arrayList.size() == 0) {
llEmptyFile.setVisibility(View.VISIBLE);
} else {
llEmptyFile.setVisibility(View.GONE);
}
loading.setVisibility(View.GONE);
adapterMusicSearch.notifyDataSetChanged();
}
}
public static Date getFileLastModified(String pathFile) {
File file = new File(pathFile);
return new Date(file.lastModified());
}
private void initAdsFull() {
mInterstitialAd = new InterstitialAd(this);
MobileAds.initialize(this,
getResources().getString(R.string.mobile_id));
mInterstitialAd.setAdUnitId(getResources().getString(R.string.ads_full));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
finish();
}
});
}
public long getTimeVideo(String pathFile) {
try {
MediaPlayer mp = MediaPlayer.create(this, Uri.parse(pathFile));
int duration = mp.getDuration();
mp.release();
return duration;
} catch (Exception e) {
return 0;
}
}
}
public class DownloadVideoAsyn extends AsyncTask<String, Integer, String> {
private String title;
private int check;
private NotificationCompat.Builder builder;
private NotificationManager manager;
private String CHANNEL_ID = "download_video_tiktok_auto";
private String pathVideo = title + ".mp3";
private int id = 1232;
private Context mContext;
private NotificationChannel mChannel;
Notification noti;
public DownloadVideoAsyn(String title, int check, Context context) {
this.title = title;
this.check = check;
this.mContext = context;
}
public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/FreeMusic/";
private EventDownloadVideoCallBack callBack;
public void setCallBack(EventDownloadVideoCallBack callBack) {
this.callBack = callBack;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (check == 2) {
manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(mContext, CHANNEL_ID);
Intent iCancel = new Intent();
id = id + 1;
iCancel.putExtra("id", id);
iCancel.putExtra("pathVideo", pathVideo);
iCancel.setAction("CANCEL_ACTION");
PendingIntent PICancel = PendingIntent.getBroadcast(mContext, 0, iCancel, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setSmallIcon(R.drawable.ic_download)
.setContentTitle(title.replace("'", "") + ".mp3")
.setContentText(mContext.getString(R.string.download))
.setChannelId(CHANNEL_ID)
.setPriority(Notification.PRIORITY_MAX)
.addAction(R.drawable.ic_cancel, "Cancel", PICancel)
.setAutoCancel(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
mChannel = new NotificationChannel(CHANNEL_ID, "channel-name", importance);
mChannel.setSound(null, null);
manager.createNotificationChannel(mChannel);
}
}
}
#Override
protected String doInBackground(String... strings) {
String link = strings[0];
try {
URL url = new URL(link);
// check folder exist
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();
}
String path = PATH + title.replace("'", "") + ".mp3";
File file = new File(path);
long total = 0;
FileOutputStream fileOutputStream = new FileOutputStream(file);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
int fileLength = connection.getContentLength();
//=============================
byte[] b = new byte[1024];
int count = inputStream.read(b);
while (count != -1) {
total += count;
fileOutputStream.write(b, 0, count);
count = inputStream.read(b);
int progress = (int) (total * 100 / fileLength);
publishProgress(progress);
if (check == 2) {
builder.setProgress(100, progress, false);
builder.setContentText(mContext.getString(R.string.download) + " " + progress + "%");
noti = builder.build();
noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
manager.notify(id, noti);
if (progress == 100) {
manager.cancel(id);
}
}
}
inputStream.close();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
try {
URL url = new URL(link);
// check folder exist
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();
}
Date currentTime = Calendar.getInstance().getTime();
title = currentTime.getTime() + "";
String path = PATH + title + ".mp3";
File file = new File(path);
long total = 0;
FileOutputStream fileOutputStream = new FileOutputStream(file);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
int fileLength = connection.getContentLength();
//=============================
byte[] b = new byte[1024];
int count = inputStream.read(b);
while (count != -1) {
total += count;
fileOutputStream.write(b, 0, count);
count = inputStream.read(b);
int progress = (int) (total * 100 / fileLength);
publishProgress(progress);
if (check == 2) {
builder.setProgress(100, progress, false);
builder.setContentText(mContext.getString(R.string.download) + " " + progress + "%");
noti = builder.build();
noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
manager.notify(id, noti);
if (progress == 100) {
manager.cancel(id);
}
}
}
inputStream.close();
fileOutputStream.close();
} catch (Exception ex) {
return null;
}
}
return PATH + title + ".mp3";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
Uri uri = Uri.parse("file://" + "/storage/emulated/0/FreeMusic/" + s);
Intent scanFileIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
mContext.sendBroadcast(scanFileIntent);
callBack.downloadVideoFinish(s);
}
else {
callBack.downloadVideoFail("Error");
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (check == 1) {
if (callBack != null) {
callBack.updateProgress(values[0]);
}
}
}
public interface EventDownloadVideoCallBack {
void downloadVideoFinish(String s);
void updateProgress(int pro);
void downloadVideoFail(String fail);
}
}
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
In my project there is an option to download a set of files.To check the storage availability I used the below code
public static int getSDCardStatus() {
String extState = Environment.getExternalStorageState();
int status;
if (extState.equals(Environment.MEDIA_MOUNTED)) {
status = MOUNTED;
} else if (extState.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
status = READ_ONLY;
} else {
status = UNMOUNTED;
}
return status;
}
private String getLoginFolders() {
// TODO Auto-generated method stub
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
File f = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/.nomedia");
f.mkdirs();
file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/" + sotcPref.getString("domain", "") + "/"
+ sotcPref.getString("user_id", ""));
file.mkdirs();
}
return file.getAbsolutePath();
}
While making download in LG Nexus 4 and Samsung Nexus 4 working fine. But in Micromax a114 canvas 2.2 and Nexus 5 not working fine.
For reference the service class which I am using for download
public class DownloadService extends IntentService {
#Override
public void onDestroy() {
super.onDestroy();
if (Constants.DEBUG)
Log.i("StatusDownloadservice", "Ondestroy");
}
private int OFFSET;
private int LIMIT;
String data;
private final String TAG = "DownloadService";
private int result = Activity.RESULT_CANCELED;
public static int COMPLETED = 100;
public static int FAILED = 101;
public static int LOW_SPACE = 102;
public static int NETWORK_PROBLEM = 103;
public static int ASSERT_EXISIT = 104;
public static int PARTIALLY_DOWNLOADED = 105;
public static int NO_FILE = 105;
private NotificationManager notificationManager;
private Notification notification;
ConnectivityManager connMgr;
ArrayList<ConcurrentHashMap<String, String>> showAssetList;
RemoteViews contentView;
private SharedPreferences sotcPref;
PendingIntent contentIntent;
int downloadCount = 1;
String url;
String showname;
String showdatecreated;
String showId;
Messenger messenger;
int noofFiles;
Thread handleIntentThread = null;
Thread downloadJoinThread = null;
public Handler notifyHandler = new Handler();
int assetCount = 0;
// To track the app event
MixpanelAPI mMixpanel;
private SharedPreferences myPrefs;
// private boolean isServiceRunning=false;
public DownloadService() {
super("com.iw.sotc.show.offline.DownloadService");
if (Constants.DEBUG)
Log.d(TAG, "Offline step 5 " + "DownloadService()constructor");
if (Constants.DEBUG)
Log.d(TAG, "DownloadService... Constructor");
OFFSET = 0;
LIMIT = 3;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_REDELIVER_INTENT;
}
#Override
protected void onHandleIntent(Intent intent) {
if (Constants.DEBUG)
Log.i("StatusDownloadservice", "OnhandleIntent");
// Initialize the Mixpanel library for tracking and push notifications.
mMixpanel = MixpanelAPI.getInstance(this, Constants.MIXPANEL_API_TOKEN);
myPrefs = getApplicationContext().getSharedPreferences("SOTCPref",
MODE_PRIVATE);
final Intent intentCpy = intent;
// synchronized (intentCpy) {
/*
* new Thread(new Runnable() {
*
* #Override public void run() {
*/
if (Constants.DEBUG)
Log.d(TAG, "Offline step 6 " + "onHandleIntent");
connMgr = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
sotcPref = getApplicationContext().getSharedPreferences("SOTCPref",
MODE_PRIVATE);
if (Constants.DEBUG)
Log.d(TAG, "onHandleIntent.........");
Bundle extras = intentCpy.getExtras();
url = extras.getString("url");
showname = extras.getString("showname");
showdatecreated = extras.getString("showdatecreated");
// sara
if (showdatecreated.contains("/")) {
data = showdatecreated.replaceAll("/", "#");
if (Constants.DEBUG) {
System.out.println("date");
System.out.println(data);
}
} else {
data = showdatecreated;
if (Constants.DEBUG) {
System.out.println("date in else");
System.out.println(showdatecreated);
System.out.println(data);
}
}
showId = extras.getString("share_id");
noofFiles = extras.getInt("noofFiles");
messenger = (Messenger) extras.get("MESSENGER");
/*
* Intent notificationIntent = new Intent(); contentIntent =
* PendingIntent.getService( getApplicationContext(), 1,
* notificationIntent, 0);
*/
// contentIntent =
// PendingIntent.getActivity(getApplicationContext(), 0,
// notificationIntent, 0);
showNotification();
if (Constants.DEBUG)
Log.i("FOO", "Notification started");
if (showname.length() > 18)
showname = showname.substring(0, 17);
if (DownloadAssets.TOTAL_ASSET_COUNT == 0) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 7 "
+ "if(DownloadAssets.TOTAL_ASSET_COUNT == 0)");
Log.i("Downloadassetvalue", ""
+ DownloadAssets.TOTAL_ASSET_COUNT);
}
// TODO Auto-generated method stub
downloadSetofAssets(OFFSET, LIMIT, url);
assetCount = DownloadAssets.TOTAL_ASSET_COUNT;
if (Constants.DEBUG)
Log.d(TAG, "Offline step 7 asset count :" + assetCount);
DownloadAssets.TOTAL_ASSET_COUNT = 0;
}
if (assetCount > LIMIT) {
if (Constants.DEBUG)
Log.d(TAG, "Offline step 7.1 "
+ "if(DownloadAssets.TOTAL_ASSET_COUNT > LIMIT)");
for (OFFSET = LIMIT; OFFSET < assetCount;) {
if (Constants.DEBUG)
Log.d(TAG,
"Offline step 8.1 "
+ "for(OFFSET = LIMIT; OFFSET < DownloadAssets.TOTAL_ASSET_COUNT;)");
downloadSetofAssets(OFFSET, LIMIT, url);
OFFSET = OFFSET + LIMIT;
}
DownloadAssets.TOTAL_ASSET_COUNT = 0;
}
if (Constants.DEBUG)
Log.d(TAG, "download check :downloadJoinThread is running");
if (Constants.DEBUG)
Log.i("DownloadingStatus", "InService");
if (downloadCount >= 1) {
result = DownloadService.COMPLETED;
// to notify the changes made after the offline
// coded by Karthikeyan V
showNotificationDownloadComplete("download successful.");
Message msg = Message.obtain();
try {
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "Sendmessenger");
msg.arg1 = result;
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(), "Exception sending message", e1);
}
} else {
result = DownloadService.FAILED;
Message msg = Message.obtain();
msg.arg1 = result;
try {
messenger.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// stopForeground(true);
/*
* notification.setLatestEventInfo(DownloadService.this,
* "Download Failed", "", contentIntent);
*/
showNotificationDownloadComplete("download failed.");
}
/*
* }
*
* }).start();
*/
/*
* //to notify the changes made after the offline
* ViewShowList.showListadapter.notifyDataSetChanged();
*/
// }
}
private void showNotificationDownloadComplete(String statusDownload) {
notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.sotc_notification_icon, "",
System.currentTimeMillis());
contentView = new RemoteViews(getPackageName(),
R.layout.upload_progress_aftercomplete);
notification.flags |= Notification.FLAG_NO_CLEAR;
contentView
.setImageViewResource(R.id.imageOfflineshowCompletion, R.drawable.icon);
contentView.setTextViewText(R.id.textView1offlineshowCompletion, showname+"\t"+statusDownload);
//For click event
Intent intentOpenOfflineshows = new Intent(this,
com.iw.sotc.show.offline.ViewOfflineShows.class);
contentIntent = PendingIntent.getActivity(this, 2,
intentOpenOfflineshows, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_SHOW_LIGHTS;
notification.contentIntent = contentIntent;
notification.contentView = contentView;
notificationManager.notify(1, notification);
}
private void showNotification() {
notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.sotc_notification_icon, "",
System.currentTimeMillis());
contentView = new RemoteViews(getPackageName(),
R.layout.upload_progress_bar);
notification.flags |= Notification.FLAG_NO_CLEAR;
contentView
.setImageViewResource(R.id.imageOfflineshow, R.drawable.icon);
contentView.setTextViewText(R.id.textView1, showname);
contentView.setProgressBar(R.id.progressBar1, 100, 0, false);
notification.contentIntent = contentIntent;
notification.contentView = contentView;
notificationManager.notify(1, notification);
/*
* notificationManager = (NotificationManager) this
* .getSystemService(Context.NOTIFICATION_SERVICE); notification = new
* Notification( R.drawable.sotc_notification_icon, "", System
* .currentTimeMillis()); notification.flags = notification.flags |
* Notification.FLAG_ONGOING_EVENT; notification.flags|=
* Notification.FLAG_NO_CLEAR; notification.contentView = new
* RemoteViews( getApplicationContext().getPackageName(),
* R.layout.upload_progress_bar); notification.icon =
* R.drawable.sotc_notification_icon;
* notification.contentView.setTextViewText(R.id.textView1, showname);
* notification.contentIntent = contentIntent;
* notification.contentView.setProgressBar(R.id.progressBar1, 100, 0,
* false); notificationManager.notify(1, notification);
* startForeground(1, notification);
*/
}
private void downloadSetofAssets(int OFFSET, int LIMIT, String url) {
if (Constants.DEBUG)
Log.d(TAG, "Offline step 8 " + "downloadSetofAssets");
if (Constants.DEBUG)
try {
url = url.replace("value1",
URLEncoder.encode("" + OFFSET, "UTF-8"));
url = url.replace("value2",
URLEncoder.encode("" + LIMIT, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (Constants.DEBUG)
Log.i(TAG, "Show offline -- Asset URL: " + url);
showAssetList = DownloadAssets.hit(getApplicationContext(), url);
for (ConcurrentHashMap<String, String> asset : showAssetList) {
String thumbUrl = asset.get("thumb_url");
// String normalUrl = asset.get("normal_url");
// added by Karthikeyan v
// To avoid downloading png file for document type files
// here just used the variable name as normalUrl for testing purpose
// // do not confuse
String largeUrl = asset.get("large_url");
String normalUrl = asset.get("normal_url");
String mp4Url = asset.get("mp4_url");
String fileType = asset.get("filetype");
String assetID = asset.get("id");
String assetType = asset.get("asset_type");
if (Constants.DEBUG)
Log.d(TAG, "Thumb Url :" + thumbUrl);
if (Constants.DEBUG)
Log.d(TAG, "Normal Url :" + normalUrl);
if (Constants.DEBUG)
Log.d(TAG, "Asset ID : " + assetID);
if (Constants.DEBUG)
Log.d(TAG, "Asset Type : " + assetType);
if (Constants.DEBUG)
Log.d(TAG, "MP4 Url : " + mp4Url);
if (Constants.DEBUG)
Log.d(TAG, "FileType : " + fileType);
if (assetType.equals("1")) { // Image
File assetDirectory = createAssetDirectory(showId, showname,
data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(),
"/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(),
"/Normal." + getExtention(normalUrl));
if (Constants.DEBUG)
Log.i("NormalFilepath", normalFile.getAbsolutePath());
if (Constants.DEBUG)
Log.d(TAG,
"Normal File path: "
+ normalFile.getAbsolutePath());
doInBackground(this, normalUrl,
normalFile.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
}
} else if (assetType.equals("2")) { // Video
File assetDirectory = createAssetDirectory(showId, showname,
data, assetID, assetType);
if (assetDirectory != null) {
if (!fileType.equals("Youtube")) { // via AddLink
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File mp4url = new File(
assetDirectory.getAbsolutePath(), "/Normal");
mp4url.mkdirs();
// mp4_Url
File mp4File = new File(mp4url.getAbsolutePath(),
"/Normal." + getExtention(mp4Url));
if (Constants.DEBUG)
Log.d(TAG,
"Normal File path: "
+ mp4File.getAbsolutePath());
doInBackground(this, mp4Url,
mp4File.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
} else if (Constants.DEBUG)
Log.d(TAG,
"Asset type is video but is Youtube link. So not proceeding for offline");
}
} else if (assetType.equals("3")) { // Audio
File assetDirectory = createAssetDirectory(showId, showname,
data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(),
"/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(),
"/Normal." + getExtention(normalUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Normal File path: "
+ normalFile.getAbsolutePath());
doInBackground(this, normalUrl,
normalFile.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
}
} else {
if (!assetType.equals("5")) {
File assetDirectory = createAssetDirectory(showId,
showname, data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File normal = new File(
assetDirectory.getAbsolutePath(), "/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(),
"/Normal." + getExtention(largeUrl));
if (Constants.DEBUG)
Log.i("Normal File path: ",
normalFile.getAbsolutePath());
doInBackground(this, largeUrl,
normalFile.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
} else // "5" Link
{
if (Constants.DEBUG)
Log.d(TAG, "This is Web Link");
}
}
}
}
}
private String getLoginFolders() {
// TODO Auto-generated method stub
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
File f = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/.nomedia");
f.mkdirs();
file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/" + sotcPref.getString("domain", "") + "/"
+ sotcPref.getString("user_id", ""));
file.mkdirs();
}
return file.getAbsolutePath();
}
private File createAssetDirectory(String showid, String showname,
String data, String assetID, String assetType) {
// TODO Auto-generated method stub
if (Constants.DEBUG)
Log.d(TAG, "Offline step 10 " + "createAssetDirectory");
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
if (DownloadAssets.TOTAL_ASSET_COUNT != 0) {
/**
* From to concept here is to avoid duplication of new offline
* shows when show is updated. So, we are here renaming previous
* offline show's folder name with updated asset count.
*/
boolean isRenameSuccess = false;
File f = new File(getLoginFolders());
if (!f.exists())
f.mkdirs();
File[] fileArray = f.listFiles();
File f2 = new File(getLoginFolders(), "/" + showid.trim() + ","
+ showname.trim() + "," + data);
for (File from : fileArray) {
String s1 = from.getName().substring(0,
from.getName().lastIndexOf(","));
if (Constants.DEBUG)
Log.i(TAG, "s1: " + s1);
if (f2.getName().equalsIgnoreCase(s1)) {
// Rename
File to = new File(getLoginFolders(), "/"
+ showid.trim() + "," + showname.trim() + ","
+ data + "," + noofFiles);
if (Constants.DEBUG)
Log.i(TAG, "from existence: " + from.exists());
try {
isRenameSuccess = from.renameTo(to);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Constants.DEBUG)
Log.i(TAG, "isRenameSuccess: " + isRenameSuccess);
break;
}
}
file = new File(getLoginFolders(), "/" + showid.trim() + ","
+ showname.trim() + "," + data + "," + noofFiles
+ "/File_" + assetID + "," + assetType.trim());
}
if (file != null)
if (!file.exists())
file.mkdirs();
}
return file;
}
public static String getExtention(String url) {
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return extension;
}
boolean doInBackground(Context context, String urlPath,
String destinationPath, Messenger messenger) {
final String desti = destinationPath;
final String url = urlPath;
final Messenger messengerCopy = messenger;
final Context cntxt = context;
/*
* new Thread(new Runnable() {
*
* #Override public void run() {
*/
if (Constants.DEBUG)
Log.d(TAG, "Offline step 9 " + "doInBackground");
// boolean isDownloaded = false;
int lastPercent = 0;
File destination = new File(desti);
if (Constants.DEBUG)
Log.i("DestinationFile", destination.getAbsolutePath());
if (!destination.exists()) {
if (chkConnectionStatus()) {
InputStream stream = null;
FileOutputStream fos = null;
try {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
stream = conn.getInputStream();
int contentLength = conn.getContentLength();
if (Constants.DEBUG)
Log.i(TAG, "contentLength : " + contentLength);
if (contentLength == 0) {
result = DownloadService.NO_FILE;
destination.delete();
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.Text_NoFile),
1000).show();
} else if (contentLength > availablestorageOnExternalDir()) {
// No Space Available
result = DownloadService.LOW_SPACE;
destination.delete();
Toast.makeText(
getApplicationContext(),
getResources().getString(
R.string.Text_NoSpaceShow), 1000)
.show();
} else {
fos = new FileOutputStream(destination.getPath());
long total = 0l;
final int buffer_size = 4 * 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = stream.read(bytes, 0, buffer_size);
if (count == -1)
break;
fos.write(bytes, 0, count);
total += count;
int percent = (int) ((total * 100) / contentLength);
if (percent > lastPercent) {
if (Constants.DEBUG)
Log.i("Percent", "" + percent);
contentView.setProgressBar(
R.id.progressBar1, 100, percent,
false);
notification.contentView = contentView;
lastPercent = percent;
if (Constants.DEBUG)
Log.i("DownloadingPercent", ""
+ percent);
}
}
if (destination.length() < contentLength) {
result = DownloadService.PARTIALLY_DOWNLOADED;
destination.delete();
} else {
if (Constants.DEBUG)
Log.e(TAG,
"Sucessful downloaded-------------------------------------------------"
+ downloadCount++);
// Sucessful finished
if (Constants.DEBUG)
Log.e(TAG,
"Sucessful downloaded-------------------------------------------------"
+ downloadCount);
result = Activity.RESULT_OK;
}
} catch (Exception ex) {
}
// To track the offline event
JSONObject properties = new JSONObject();
try {
properties.put("User Name",
myPrefs.getString("email_id", null));
properties.put("MAIL",
myPrefs.getString("email_id", null));
} catch (JSONException e) {
}
mMixpanel.identify(myPrefs.getString("email_id", null));
mMixpanel.getPeople().set(properties);
mMixpanel.track("mA_Show Offline End", properties);
}
conn.disconnect();
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messengerCopy.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(),
"Exception sending message", e1);
}
if (Constants.DEBUG)
Log.v(TAG, "Completed.............. ");
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
// / no network connection
result = DownloadService.NETWORK_PROBLEM;
notification.setLatestEventInfo(cntxt,
"Please check your network connection", "",
contentIntent);
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messengerCopy.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(),
"Exception sending message", e1);
}
}
} else {
result = DownloadService.ASSERT_EXISIT;
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messengerCopy.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
/*
* }
*
* }).start();
*/
return true;
}
public long availablestorageOnExternalDir() // Get Available space(in Bytes)
{
StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
long bytesAvailable = (long) stat.getBlockSize()
* (long) stat.getAvailableBlocks();
long megAvailable = bytesAvailable / (1024 * 1024);
if (Constants.DEBUG)
Log.e("", "Available MB : " + megAvailable);
if (Constants.DEBUG)
Log.e("", "Available Bytes : " + bytesAvailable);
return bytesAvailable;
}
public boolean chkConnectionStatus() {
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
if (wifi.isConnected())
return true;
return false;
} else if (mobile.isAvailable()) {
if (mobile.isConnected())
return true;
return false;
} else
return false;
}
}
My queries :
1.Is anything need to check additionally?
2.Is the folder structure is different in many android devices?
3.If the android devices having different folder structure or storage options(internal or external) how can I look forward?
I am using a service in my mp3 player to play media. I use mediaplayer object to play music. Normally the volume keys work when the music is playing. I also used Telephony Manager in my service to check phone calls. And I start and stop the music when the call is disconnected and is in progress respectively. But after the disconnection of phone call, the volume keys stopped working. I can see the dialog of volume change. But the sound volume don't change. Any idea? It is even happening in native player.
My player service:
public class PPlayService extends Service {
public static final int NOTIFICATION_NUMBER = 0;
Context conte;
MediaPlayer playHandler;
BroadcastReceiver broadcaster;
IncomingHandler mServiceHandler;
String online = "", link = "", name = "";
boolean playing = false;
boolean currentFlag = true;
Runnable runnable;
String[] uris, names;
int send;
SharedPreferences pre;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
AudioManager am;
// ........
PhoneStateListener phoneStateListener;
TelephonyManager mgr;
boolean notFromTelephone = false;
RemoteViews contentView;
BroadcastReceiver stopFromNoti, forwardFromNoti, backwardFromNoti;
Thread th;
public void handleMessage(Message msg) {
try {
playing = false;
if (playHandler != null) {
playHandler.setOnPreparedListener(null);
playHandler.setOnCompletionListener(null);
}
currentFlag = true;
System.gc();
if (online.equals("0")) {
contentView = new RemoteViews(getPackageName(),
R.layout.offline_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0,
new Intent("stopfromnoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti,
pit);
PendingIntent backSong = PendingIntent.getBroadcast(conte, 0,
new Intent("backwardFromNoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.backward_noti,
backSong);
PendingIntent frontSong = PendingIntent.getBroadcast(conte, 0,
new Intent("forwardFromNoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.forward_noti,
frontSong);
} else {
contentView = new RemoteViews(getPackageName(),
R.layout.online_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0,
new Intent("stopfromnoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti,
pit);
}
Intent intt = new Intent(getBaseContext(), MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0,
intt, 0);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon).setContent(contentView)
.setContentIntent(pi).setAutoCancel(false);
notificationManager.notify(
Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.build());
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.LOADING);
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
conte.sendBroadcast(in);
if (playHandler != null) {
playing = false;
playHandler.reset();
} else {
playHandler = new MediaPlayer();
}
if (online.equals("1")) {
// Online Stream
playHandler.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
playHandler.setDataSource(link);
playHandler.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
if (playHandler != null) {
if (!playHandler.isPlaying()) {
playSongNow();
}
}
}
});
playHandler.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Offline Stream
playHandler = MediaPlayer.create(conte, Uri.parse(link));
playSongNow();
}
} catch (Exception e) {
}
}
#Override
public void onCreate() {
conte = this;
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(new OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
}
}, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
forwardFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
getSD();
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i >= send - 1) {
if (send > 0) {
name = names[0];
link = uris[0];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i + 1];
link = uris[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
}
};
backwardFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
getSD();
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i == send || i == 0) {
if (send > 0) {
name = names[send - 1];
link = uris[send - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i - 1];
link = uris[i - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
}
};
stopFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playing = false;
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("status", Mp3Constants.COMPLETED);
in.putExtra("name", name);
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime", playHandler.getDuration() / 1000);
conte.sendBroadcast(in);
playHandler.reset();
stopSelf();
}
stopSelf();
}
};
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
if (playHandler != null)
if (playHandler.isPlaying()) {
playing = false;
playHandler.pause();
}
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
if (!notFromTelephone) {
notFromTelephone = false;
if (playHandler != null)
if (!playHandler.isPlaying()) {
playSongNow();
}
}
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
if (playHandler.isPlaying()) {
playing = false;
playHandler.pause();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};
mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
pre = getSharedPreferences("download", 0);
online = pre.getString("online", "0");
link = pre.getString("link", "");
name = pre.getString("name", "");
contentView = new RemoteViews(getPackageName(),
R.layout.online_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0, new Intent(
"stopfromnoti"), PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti, pit);
notificationManager = (NotificationManager) conte
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon).setContent(contentView)
.setAutoCancel(false).setContentIntent(pit);
startForeground(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.build());
broadcaster = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getExtras().getInt("action") == Mp3Constants.PAUSE) {
if (playHandler != null)
if (playHandler.isPlaying()) {
playing = false;
notFromTelephone = true;
playHandler.pause();
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.PLAY) {
if (playHandler != null)
if (!playHandler.isPlaying()) {
playSongNow();
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.STOP) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
stopSelf();
} else if (arg1.getExtras().getInt("action") == Mp3Constants.SEEK) {
if (playHandler != null) {
{
playHandler.seekTo(arg1.getExtras()
.getInt("seekto") * 1000);
}
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.FORWARD) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
for (int i = 0; i < send - 1; i++) {
if (link.equalsIgnoreCase(uris[i])) {
link = uris[i + 1];
name = names[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
break;
}
}
}
}
// getSD();
// int i = 0;
// for (i = 0; i < send; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// break;
// }
// }
// if (i >= send - 1) {
// if (send > 0) {
// name = names[0];
// link = uris[0];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
// } else {
// name = names[i + 1];
// link = uris[i + 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
} else if (arg1.getExtras().getInt("action") == Mp3Constants.BACKWARD) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i == send || i == 0) {
if (send > 0) {
name = names[send - 1];
link = uris[send - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i - 1];
link = uris[i - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
// for (int i = 0; i < send - 1; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// link = uris[i - 1];
// name = names[i - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler
// .obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// break;
// }
// }
}
}
// getSD();
// int i = 0;
// for (i = 0; i < send; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// break;
// }
// }
// if (i == send || i == 0) {
// if (send > 0) {
// name = names[send - 1];
// link = uris[send - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
// } else {
// name = names[i - 1];
// link = uris[i - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
}
}
};
registerReceiver(broadcaster, new IntentFilter(
"com.codebrew.bestmp3downloader.PPlayService"));
registerReceiver(stopFromNoti, new IntentFilter("stopfromnoti"));
registerReceiver(forwardFromNoti, new IntentFilter("forwardFromNoti"));
registerReceiver(backwardFromNoti, new IntentFilter("backwardFromNoti"));
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();
mServiceHandler = new IncomingHandler(PPlayService.this);
}
#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");
online = pre.getString("online", "0");
link = pre.getString("link", "");
name = pre.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() {
unregisterReceiver(broadcaster);
unregisterReceiver(stopFromNoti);
unregisterReceiver(forwardFromNoti);
unregisterReceiver(backwardFromNoti);
if (playHandler != null) {
if (playHandler.isPlaying()) {
playHandler.stop();
}
playHandler = null;
}
if (mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
super.onDestroy();
notificationManager.cancel(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER);
}
public void playSongNow() {
try {
playing = true;
playHandler.start();
runnable = new Runnable() {
public void run() {
while (playing) {
if (playing) {
try {
Intent in = new Intent(
Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.PLAYING);
if (playHandler.getCurrentPosition() / 1000 == playHandler
.getDuration() / 1000)
th.stop();
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime",
playHandler.getDuration() / 1000);
if (currentFlag) {
currentFlag = false;
contentView.setTextViewText(
R.id.name_of_the_song, name);
notificationManager
.notify(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.setContent(
contentView)
.build());
}
conte.sendBroadcast(in);
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
th = new Thread(runnable);
th.start();
playHandler.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
playing = false;
pre.edit().putBoolean("stopped", true).commit();
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("status", Mp3Constants.COMPLETED);
in.putExtra("name", name);
try {
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime",
playHandler.getDuration() / 1000);
} catch (Exception e) {
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
}
conte.sendBroadcast(in);
if (online.equals("0")) {
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
for (int i = 0; i < send - 1; i++) {
if (link.equalsIgnoreCase(uris[i])) {
link = uris[i + 1];
name = names[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
break;
}
}
}
}
}
if (online.equals("1")) {
// stopSelf();
}
}
});
} catch (Exception e) {
playing = false;
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.FAILED);
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
conte.sendBroadcast(in);
Toast.makeText(
getBaseContext(),
"Error playing: "
+ name
+ "\nFile broken or deleted! Please try another song",
Toast.LENGTH_SHORT).show();
stopSelf();
}
}
private void getSD() {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return;
}
Arrays.sort(files, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
if (((File) o1).lastModified() > ((File) o2).lastModified()) {
return +1;
} else if (((File) o1).lastModified() < ((File) o2)
.lastModified()) {
return -1;
} else {
return 0;
}
}
});
send = files.length;
uris = new String[send];
names = new String[send];
for (int i = 0; i < send; i++) {
File file = files[i];
// take the file name only
double size = file.length();
size = size / (1024 * 1024);
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
uris[send - 1 - i] = file.getPath();
names[send - 1 - i] = myfile;
}
}
static class IncomingHandler extends Handler {
private final WeakReference<PPlayService> mService;
IncomingHandler(PPlayService service) {
mService = new WeakReference<PPlayService>(service);
}
#Override
public void handleMessage(Message msg) {
PPlayService service = mService.get();
if (service != null) {
service.handleMessage(msg);
}
}
}
}
I am trying to download files using IntentService.My downloading queue is interrupted.
I am using the following code to start a service
Intent intent = new Intent(ViewShowList.this, DownloadService.class);
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
intent.putExtra("url", url);
intent.putExtra("share_id", showID);
intent.putExtra("showname", name);
intent.putExtra("showdatecreated", dateCreated);
intent.putExtra("noofFiles", noofFiles);
startService(intent);
Handler for communication back
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
public void handleMessage(Message message) {
Log.d(TAG, "handleMessage.....................");
//Object path = message.obj;
if (message.arg1 == DownloadService.COMPLETED) {
Toast.makeText(mContext, getResources().getString(R.string.Text_MadeOffline), Toast.LENGTH_SHORT).show();
createOfflineShowsList();
syncShowAssets();
if (showListadapter != null) {
showListadapter.notifyDataSetChanged();
}
} else {
Log.e(TAG, "Download Failed...");
}
}
};
DownloadService.java
This is service class which extend IntentService
public class DownloadService
extends IntentService {
private int OFFSET;
private int LIMIT;
String data;
private final String TAG = "DownloadService";
private int result = Activity.RESULT_CANCELED;
public static int COMPLETED = 100;
public static int FAILED = 101;
public static int LOW_SPACE = 102;
public static int NETWORK_PROBLEM = 103;
public static int ASSERT_EXISIT = 104;
public static int PARTIALLY_DOWNLOADED = 105;
public static int NO_FILE = 105;
private NotificationManager notificationManager;
private Notification notification;
ConnectivityManager connMgr;
ArrayList<HashMap<String, String>> showAssetList;
private SharedPreferences sotcPref;
PendingIntent contentIntent;
int i = 1;
String url;
String showname;
String showdatecreated;
String showId;
Messenger messenger;
int noofFiles;
public DownloadService() {
super("DownloadService");
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 5 " + "DownloadService()constructor");
}
if (Constants.DEBUG) {
Log.d(TAG, "DownloadService... Constructor");
}
OFFSET = 0;
LIMIT = 3;
}
#SuppressWarnings("deprecation")
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 6 " + "onHandleIntent");
}
connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
sotcPref = getApplicationContext().getSharedPreferences("SOTCPref", MODE_PRIVATE);
if (Constants.DEBUG) {
Log.d(TAG, "onHandleIntent.........");
}
Bundle extras = intent.getExtras();
url = extras.getString("url");
showname = extras.getString("showname");
showdatecreated = extras.getString("showdatecreated");
//sara
if (showdatecreated.contains("/")) {
data = showdatecreated.replaceAll("/", "#");
if (Constants.DEBUG) {
System.out.println("date");
}
if (Constants.DEBUG) {
System.out.println(data);
}
} else {
data = showdatecreated;
if (Constants.DEBUG) {
System.out.println("date in else");
}
if (Constants.DEBUG) {
System.out.println(showdatecreated);
}
if (Constants.DEBUG) {
System.out.println(data);
}
}
showId = extras.getString("share_id");
noofFiles = extras.getInt("noofFiles");
messenger = (Messenger) extras.get("MESSENGER");
Intent notificationIntent = new Intent();
contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
notification = new Notification(R.drawable.sotc_notification_icon, "", System.currentTimeMillis());
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
notification.contentView = new RemoteViews(getApplicationContext()
.getPackageName(), R.layout.upload_progress_bar);
notification.icon = R.drawable.sotc_notification_icon;
notification.contentView.setTextViewText(R.id.textView1, showname);
notification.contentIntent = contentIntent;
notification.contentView.setProgressBar(R.id.progressBar1, 100, 0, false);
notificationManager.notify(1, notification);
if (Constants.DEBUG) {
Log.i("FOO", "Notification started");
}
if (showname.length() > 18) {
showname = showname.substring(0, 17);
}
if (DownloadAssets.TOTAL_ASSET_COUNT == 0) {
downloadSetofAssets(OFFSET, LIMIT, url);
if (DownloadAssets.TOTAL_ASSET_COUNT > LIMIT) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 8 " + "if(DownloadAssets.TOTAL_ASSET_COUNT > LIMIT)");
}
for (OFFSET = LIMIT; OFFSET < DownloadAssets.TOTAL_ASSET_COUNT; ) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 8.1 " + "if(DownloadAssets.TOTAL_ASSET_COUNT > LIMIT)");
}
downloadSetofAssets(OFFSET, LIMIT, url);
OFFSET = OFFSET + LIMIT;
}
}
}
if (i > 1) {
result = DownloadService.COMPLETED;
notification.setLatestEventInfo(DownloadService.this, "Downloaded Successfully", "", contentIntent);
Message msg = Message.obtain();
msg.arg1 = result;
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
} else {
result = DownloadService.FAILED;
notification.setLatestEventInfo(DownloadService.this, "Downloaded Failed", "", contentIntent);
if (Constants.DEBUG) {
Log.e(TAG, "Download Failed...");
}
}
notification.contentView.setImageViewResource(R.id.image, R.drawable.icon);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
}
private void downloadSetofAssets(int OFFSET, int LIMIT, String url) {
// TODO Auto-generated method stub
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 7 " + "downloadSetofAssets");
}
try {
url = url.replace("value1", URLEncoder.encode("" + OFFSET, "UTF-8"));
url = url.replace("value2", URLEncoder.encode("" + LIMIT, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Constants.DEBUG) {
Log.i(TAG, "Show offline -- Asset URL: " + url);
}
showAssetList = DownloadAssets.hit(getApplicationContext(), url);
for (HashMap<String, String> asset : showAssetList) {
String thumbUrl = asset.get("thumb_url");
String normalUrl = asset.get("normal_url");
String mp4Url = asset.get("mp4_url");
String fileType = asset.get("filetype");
String assetID = asset.get("id");
String assetType = asset.get("asset_type");
if (Constants.DEBUG) {
Log.d(TAG, "Thumb Url :" + thumbUrl);
}
if (Constants.DEBUG) {
Log.d(TAG, "Normal Url :" + normalUrl);
}
if (Constants.DEBUG) {
Log.d(TAG, "Asset ID : " + assetID);
}
if (Constants.DEBUG) {
Log.d(TAG, "Asset Type : " + assetType);
}
if (Constants.DEBUG) {
Log.d(TAG, "MP4 Url : " + mp4Url);
}
if (Constants.DEBUG) {
Log.d(TAG, "FileType : " + fileType);
}
boolean isDownloaded = false;
if (assetType.equals("1")) { // Image
File assetDirectory = createAssetDirectory(showId, showname, data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(), "/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(), "/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Thumb File ath : " + thumbFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, thumbUrl, thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(), "/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(), "/Normal." + getExtention(normalUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Normal File path: " + normalFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, normalUrl, normalFile.getAbsolutePath(), messenger);
}
} else if (assetType.equals("2")) { // Video
File assetDirectory = createAssetDirectory(showId, showname, data, assetID, assetType);
if (assetDirectory != null) {
if (!fileType.equals("Youtube")) { // via AddLink
File thumb = new File(assetDirectory.getAbsolutePath(), "/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(), "/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Thumb File ath : " + thumbFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, thumbUrl, thumbFile.getAbsolutePath(), messenger);
File mp4url = new File(assetDirectory.getAbsolutePath(), "/Normal");
mp4url.mkdirs();
// mp4_Url
File mp4File = new File(mp4url.getAbsolutePath(), "/Normal." + getExtention(mp4Url));
if (Constants.DEBUG) {
Log.d(TAG, "Normal File path: " + mp4File.getAbsolutePath());
}
isDownloaded = doInBackground(this, mp4Url, mp4File.getAbsolutePath(), messenger);
} else if (Constants.DEBUG) {
Log.d(TAG, "Asset type is video but is Youtube link. So not proceeding for offline");
}
}
} else if (assetType.equals("3")) { // Audio
File assetDirectory = createAssetDirectory(showId, showname, data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(), "/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(), "/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Thumb File ath : " + thumbFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, thumbUrl, thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(), "/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(), "/Normal." + getExtention(normalUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Normal File path: " + normalFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, normalUrl, normalFile.getAbsolutePath(), messenger);
}
} else {
if (!assetType.equals("5")) {
File assetDirectory = createAssetDirectory(showId, showname, data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(), "/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(), "/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Thumb File ath : " + thumbFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, thumbUrl, thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(), "/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(), "/Normal." + getExtention(normalUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Normal File path: " + normalFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, normalUrl, normalFile.getAbsolutePath(), messenger);
} else { //"5" Link
if (Constants.DEBUG) {
Log.d(TAG, "This is Web Link");
}
isDownloaded = true;
}
}
}
}
}
private String getLoginFolders() {
// TODO Auto-generated method stub
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/.nomedia");
f.mkdirs();
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/" + sotcPref.getString("domain", "") + "/" + sotcPref.getString("user_id", ""));
file.mkdirs();
}
return file.getAbsolutePath();
}
private File createAssetDirectory(String showid, String showname,
String data, String assetID, String assetType) {
// TODO Auto-generated method stub
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 10 " + "createAssetDirectory");
}
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
if (DownloadAssets.TOTAL_ASSET_COUNT != 0) {
/**
* From to concept here is to avoid duplication of new
* offline shows when show is updated. So, we are here
* renaming previous offline show's folder name with
* updated asset count.
*/
boolean isRenameSuccess = false;
File f = new File(getLoginFolders());
if (!f.exists()) {
f.mkdirs();
}
File[] fileArray = f.listFiles();
File f2 = new File(getLoginFolders(), "/"
+ showid.trim() + ","
+ showname.trim() + ","
+ data);
for (File from : fileArray) {
String s1 = from.getName().substring(0, from.getName().lastIndexOf(","));
if (Constants.DEBUG) {
Log.i(TAG, "s1: " + s1);
}
if (f2.getName().equalsIgnoreCase(s1)) {
//Rename
File to = new File(getLoginFolders(), "/"
+ showid.trim() + ","
+ showname.trim() + ","
+ data + ","
+ noofFiles);
if (Constants.DEBUG) {
Log.i(TAG, "from existence: " + from.exists());
}
try {
isRenameSuccess = from.renameTo(to);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Constants.DEBUG) {
Log.i(TAG, "isRenameSuccess: " + isRenameSuccess);
}
break;
}
}
file = new File(getLoginFolders(), "/"
+ showid.trim() + ","
+ showname.trim() + ","
+ data + ","
+ noofFiles +
"/File_"
+ assetID + ","
+ assetType.trim());
}
if (file != null) {
if (!file.exists()) {
file.mkdirs();
}
}
}
return file;
}
public static String getExtention(String url) {
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return extension;
}
#SuppressWarnings({"deprecation", "deprecation"})
boolean doInBackground(Context context, String urlPath, String destinationPath, Messenger messenger) {
boolean isDownloaded = false;
int lastPercent = 0;
File destination = new File(destinationPath);
if (!destination.exists()) {
if (chkConnectionStatus()) {
InputStream stream = null;
FileOutputStream fos = null;
try {
URL imageUrl = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
stream = conn.getInputStream();
int contentLength = conn.getContentLength();
if (Constants.DEBUG) {
Log.i(TAG, "contentLength : " + contentLength);
}
if (contentLength == 0) {
result = DownloadService.NO_FILE;
destination.delete();
isDownloaded = false;
Toast.makeText(getApplicationContext(), getResources().getString(R.string.Text_NoFile), 1000).show();
} else if (contentLength > availablestorageOnExternalDir()) {
//No Space Available
result = DownloadService.LOW_SPACE;
destination.delete();
isDownloaded = false;
Toast.makeText(getApplicationContext(), getResources().getString(R.string.Text_NoSpaceShow), 1000).show();
} else {
fos = new FileOutputStream(destination.getPath());
long total = 0l;
final int buffer_size = 4 * 1024;
try {
byte[] bytes = new byte[buffer_size];
for (; ; ) {
int count = stream.read(bytes, 0, buffer_size);
if (count == -1) {
break;
}
fos.write(bytes, 0, count);
total += count;
int percent = (int) ((total * 100) / contentLength);
if (percent > lastPercent) {
notification.contentView.setProgressBar(R.id.progressBar1, 100, percent, false);
lastPercent = percent;
}
}
if (destination.length() < contentLength) {
result = DownloadService.PARTIALLY_DOWNLOADED;
destination.delete();
isDownloaded = false;
} else {
if (Constants.DEBUG) {
Log.e(TAG, "Sucessful downloaded-------------------------------------------------" + i++);
}
// Sucessful finished
//i++;
result = Activity.RESULT_OK;
isDownloaded = true;
}
} catch (Exception ex) {
}
}
conn.disconnect();
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
if (Constants.DEBUG) {
Log.v(TAG, "Completed.............. ");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
/// no network connection
result = DownloadService.NETWORK_PROBLEM;
notification.setLatestEventInfo(context, "Please check your network connection", "", contentIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
isDownloaded = true;
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
}
} else {
result = DownloadService.ASSERT_EXISIT;
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
isDownloaded = true;
}
return isDownloaded;
}
public long availablestorageOnExternalDir() //Get Available space(in Bytes)
{
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
long megAvailable = bytesAvailable / (1024 * 1024);
if (Constants.DEBUG) {
Log.e("", "Available MB : " + megAvailable);
}
if (Constants.DEBUG) {
Log.e("", "Available Bytes : " + bytesAvailable);
}
return bytesAvailable;
}
public boolean chkConnectionStatus() {
final android.net.NetworkInfo wifi =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
if (wifi.isConnected()) {
return true;
}
return false;
} else if (mobile.isAvailable()) {
if (mobile.isConnected()) {
return true;
}
return false;
} else {
return false;
}
}
}
DownloadAssets.java
//To download
//files into
//created folders
public class DownloadAssets {
private static final String TAG = "DownloadAssets";
public static int TOTAL_ASSET_COUNT;
static synchronized ArrayList<HashMap<String, String>> hit(Context context, String url) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 9 " + "hit url" + url);
}
ArrayList<HashMap<String, String>> mList = new ArrayList<HashMap<String, String>>();
String message = null;
String result = null;
try {
result = Constants.queryRESTurl(url);
if (result != null) {
if (result.equals("timeout")) {
message = context.getResources().getString(R.string.Text_TimeOut);
} else {
JSONObject json = Constants.convertStringtoJsonObject(result);
try {
JSONObject results = json.getJSONObject(ThumbnailFragment.JSON_RESPONSE_ATTR_RESULTSET);
String totalAssetCount = results.getString(ThumbnailFragment.JSON_RESPONSE_ATTR_ASSET_COUNT);
TOTAL_ASSET_COUNT = Integer.parseInt(totalAssetCount);
if (Constants.DEBUG) {
Log.i("5" + TAG, "totalAssetCount : " + totalAssetCount);
}
if (TOTAL_ASSET_COUNT != 0) {
JSONArray assetData = results.getJSONArray(ThumbnailFragment.JSON_RESPONSE_ATTR_ASSET_ARRAY);
if (Constants.DEBUG) {
Log.i(TAG, "6Madhu " + assetData.toString());
}
int nObjects = assetData.length();
if (Constants.DEBUG) {
Log.i(TAG, "7Madhu " + nObjects);
}
if (nObjects != 0) {
for (int i = 0; i < nObjects; i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = assetData.getJSONObject(i);
map.put("id", "" + e.getString("assets_id"));
map.put("asset_name", "" + e.getString("asset_name"));
map.put("thumb_url", "" + e.getString("thumb_url"));
map.put("asset_type", "" + e.getString("asset_type"));
map.put("large_url", "" + e.getString("large_url"));
map.put("mp4_url", "" + e.getString("mp4_url"));
map.put("normal_url", "" + e.getString("normal_url"));
map.put("description", "" + e.getString("description"));
map.put("filetype", "" + e.getString("filetype"));
map.put("filename", "" + e.getString("original_filename"));
map.put("filesize", "" + e.getString("filesize"));
mList.add(map);
if (Constants.DEBUG) {
Log.i(TAG, "Size in Loop " + mList.size());
}
}
} else if (Constants.DEBUG) {
Log.i(TAG, "EXECUTING ELSE nObjects");
}
} else if (Constants.DEBUG) {
Log.i(TAG, "EXECUTING ELSE count");
}
} catch (JSONException e) {
if (Constants.DEBUG) {
Log.e("8log_tag", "Error parsing data " + e.toString());
}
message = context.getResources().getString(R.string.Text_InvalidResponse);
} catch (Exception e) {
if (Constants.DEBUG) {
Log.e("8log_tag", "Error parsing data " + e.toString());
}
message = context.getResources().getString(R.string.Text_InvalidResponse);
e.printStackTrace();
}
}
} else {
if (Constants.DEBUG) {
Log.i(TAG, "EXECUTING ELSE result");
}
message = context.getResources().getString(R.string.Text_InvalidResponse);
}
} catch (Exception e) {
// TODO Auto-generated catch block
message = context.getResources().getString(R.string.Text_ServerProblem);
e.printStackTrace();
}
if (Constants.DEBUG) {
Log.e(TAG, "Message : " + message);
}
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 9 End " + "hit return " + mList);
}
return mList;
}
}
My queries are
Files are downloading but not all files at first time from server.If I download more folders for example Folder1,Folder2 then Folder3, Folder1 and Folder2 interrupted(i.e 1 file is downloaded) but Folder3 downloaded fully...
How can I keep the queue of files/folders to be downloaded? !
For speed up and maintaining the queue of intent follow the below approach
protected void onHandleIntent(Intent intent) {
synchronized (intent) {
final Intent intentCpy=intent;
new Thread(new Runnable() {
#Override
public void run() {
//onHandleIntent code which is in question post
}
}
}
Use ConcurrentHashMap for Thread-Safty in following method
private synchronized void downloadSetofAssets(int OFFSET , int LIMIT , String url)
for more details about ConcurrentHashMap please visit
http://www.cs.umd.edu/class/spring2013/cmsc433/Notes/14-CMSC433-ConcurrentCollections.pdf