use of android.app.DownloadManager in project saga-android by AnandChowdhary.
the class DownloadReceiver method onReceive.
@Override
public void onReceive(final Context context, final Intent intent) {
DownloadManager dMgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Long downloadId = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
Cursor c = dMgr.query(new DownloadManager.Query().setFilterById(downloadId));
if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
final String title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
Log.d("Receiver", "Title:" + title);
if (title.equalsIgnoreCase(context.getString(R.string.app_name) + " " + context.getString(R.string.update))) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.parse(c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))), "application/vnd.android.package-archive");
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);
} else {
try {
TagOptionSingleton.getInstance().setAndroid(true);
final File file = new File(Utils.getStoragePath(context) + "/" + title);
final AudioFile f = AudioFileIO.read(file);
final Tag tag = f.getTag();
String json = readFromFile(context, title);
String url = null;
if (json != null) {
JSONObject jsonObject = new JSONObject(json);
if (jsonObject.getString("track") != null) {
if (jsonObject.getString("artist") != null) {
url = Utils.getAlbumArt(jsonObject.getString("track"), jsonObject.getString("artist"));
} else {
url = Utils.getAlbumArt(jsonObject.getString("track"), null);
}
}
if (jsonObject.getString("artist") != null)
tag.setField(FieldKey.ARTIST, jsonObject.getString("artist"));
if (jsonObject.getString("artist") != null)
tag.setField(FieldKey.ALBUM_ARTIST, jsonObject.getString("artist"));
if (jsonObject.getString("release") != null)
tag.setField(FieldKey.YEAR, jsonObject.getString("release"));
if (jsonObject.getString("trackno") != null)
tag.setField(FieldKey.TRACK, jsonObject.getString("trackno"));
if (jsonObject.getString("album") != null)
tag.setField(FieldKey.ALBUM, jsonObject.getString("album"));
if (jsonObject.getString("genre") != null)
tag.setField(FieldKey.GENRE, jsonObject.getString("genre"));
tag.setField(FieldKey.COMMENT, "Downloaded from Saga");
} else {
url = Utils.getAlbumArt(title.substring(0, title.length() - 4), null);
}
if (url != null) {
ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
FileOutputStream out = null;
try {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = context.getCacheDir();
File cover = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir);
out = new FileOutputStream(cover);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
AndroidArtwork artwork = AndroidArtwork.createArtworkFromFile(cover);
tag.setField(artwork);
Log.d(TAG, "AlbumArt deleted " + cover.delete());
} catch (Exception e) {
e.printStackTrace();
} finally {
commitAudio(context, f, file);
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}, 0, 0, null, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
commitAudio(context, f, file);
}
});
request.setShouldCache(false);
VolleySingleton.getInstance(context).addToRequestQueue(request);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
use of android.app.DownloadManager in project saga-android by AnandChowdhary.
the class MusicDownloader method startDownload.
public static void startDownload(final Context context, final String songName, final String artistName, final DownloaderListener listener) {
listener.showProgressBar();
String url = "http://162.243.144.151/new_api.php?q=" + songName.replace(" ", "%20");
if (artistName != null) {
url += "&r=" + artistName.replace(" ", "%20");
}
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.length() != 0) {
try {
final String[] fileName = new String[1];
final JSONObject jsonObject = new JSONObject(response);
String BASE_URL = "http://YouTubeInMP3.com/fetch/?video=http://www.youtube.com/watch?v=";
final DownloadManager dMgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
final String urlString = BASE_URL + jsonObject.getString("id");
final URL url = new URL(urlString);
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setInstanceFollowRedirects(true);
return urlConnection.getContentType();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
Log.d("Content type: ", result);
if ("audio/mpeg".equals(result)) {
listener.hideProgressBar();
Uri uri = Uri.parse(urlString);
DownloadManager.Request dr = new DownloadManager.Request(uri);
if (artistName == null) {
try {
fileName[0] = jsonObject.getString("title");
} catch (JSONException e) {
e.printStackTrace();
}
fileName[0].replaceAll("(?i)\\b(official|lyrics|lyric|video|song)\\b", "");
fileName[0].trim().replaceAll(" +", " ");
} else {
fileName[0] = songName;
}
fileName[0] += ".mp3";
dr.setTitle(fileName[0]);
dr.setDestinationUri(Uri.fromFile(new File(Utils.getStoragePath(context) + "/" + fileName[0])));
dMgr.enqueue(dr);
Toast.makeText(context, "Downloading...", Toast.LENGTH_SHORT).show();
listener.onSuccess();
getSongInfo(context, fileName[0].substring(0, fileName[0].length() - 4), songName, artistName);
} else {
listener.hideProgressBar();
Toast.makeText(context, "Nothing found, sorry. Try again later", Toast.LENGTH_SHORT).show();
}
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
} else {
listener.hideProgressBar();
Toast.makeText(context, "Nothing found, sorry. Try again later", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, context.getString(R.string.error_connect), Toast.LENGTH_SHORT).show();
listener.hideProgressBar();
}
});
request.setShouldCache(false);
VolleySingleton.getInstance(context).getRequestQueue().add(request);
}
use of android.app.DownloadManager in project mobile-center-sdk-android by Microsoft.
the class RemoveDownloadTask method doInBackground.
@Override
protected Void doInBackground(Void... params) {
/* This special cleanup task does not require any cancellation on state change as a previous download will never be reused. */
DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
downloadManager.remove(mDownloadId);
return null;
}
use of android.app.DownloadManager in project mobile-center-sdk-android by Microsoft.
the class CheckDownloadTask method doInBackground.
@Override
protected DownloadProgress doInBackground(Void... params) {
/*
* Completion might be triggered in background before MobileCenter.start
* if application was killed after starting download.
*
* We still want to generate the notification: if we can find the data in preferences
* that means they were not deleted, and thus that the sdk was not disabled.
*/
MobileCenterLog.debug(LOG_TAG, "Check download id=" + mDownloadId);
Distribute distribute = Distribute.getInstance();
if (mReleaseDetails == null) {
mReleaseDetails = distribute.startFromBackground(mContext);
}
/* Check intent data is what we expected. */
long expectedDownloadId = DistributeUtils.getStoredDownloadId();
if (expectedDownloadId == INVALID_DOWNLOAD_IDENTIFIER || expectedDownloadId != mDownloadId) {
MobileCenterLog.debug(LOG_TAG, "Ignoring download identifier we didn't expect, id=" + mDownloadId);
return null;
}
/* Query download manager. */
DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
try {
Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(mDownloadId));
if (cursor == null) {
throw new NoSuchElementException();
}
try {
if (!cursor.moveToFirst()) {
throw new NoSuchElementException();
}
int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_FAILED) {
throw new IllegalStateException();
}
if (status != DownloadManager.STATUS_SUCCESSFUL || mCheckProgress) {
if (mCheckProgress) {
long totalSize = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
long currentSize = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
MobileCenterLog.verbose(LOG_TAG, "currentSize=" + currentSize + " totalSize=" + totalSize);
return new DownloadProgress(currentSize, totalSize);
} else {
distribute.markDownloadStillInProgress(mReleaseDetails);
return null;
}
}
/* Build install intent. */
String localUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
MobileCenterLog.debug(LOG_TAG, "Download was successful for id=" + mDownloadId + " uri=" + localUri);
Intent intent = DistributeUtils.getInstallIntent(Uri.parse(localUri));
boolean installerFound = false;
if (intent.resolveActivity(mContext.getPackageManager()) == null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
intent = DistributeUtils.getInstallIntent(getFileUriOnOldDevices(cursor));
installerFound = intent.resolveActivity(mContext.getPackageManager()) != null;
}
} else {
installerFound = true;
}
if (!installerFound) {
MobileCenterLog.error(LOG_TAG, "Installer not found");
distribute.completeWorkflow(mReleaseDetails);
return null;
}
/* Check if a should install now. */
if (!distribute.notifyDownload(mReleaseDetails, intent)) {
/*
* This start call triggers strict mode in U.I. thread so it
* needs to be done here without synchronizing
* (not to block methods waiting on synchronized on U.I. thread)
* so yes we could launch install and SDK being disabled...
*
* This corner case cannot be avoided without triggering
* strict mode exception.
*/
MobileCenterLog.info(LOG_TAG, "Show install UI now.");
mContext.startActivity(intent);
if (mReleaseDetails != null && mReleaseDetails.isMandatoryUpdate()) {
distribute.setInstalling(mReleaseDetails);
} else {
distribute.completeWorkflow(mReleaseDetails);
}
}
} finally {
cursor.close();
}
} catch (RuntimeException e) {
MobileCenterLog.error(LOG_TAG, "Failed to download update id=" + mDownloadId, e);
distribute.completeWorkflow(mReleaseDetails);
}
return null;
}
use of android.app.DownloadManager in project android_frameworks_base by AOSPA.
the class FilesActivityUiTest method testDownload_Queued.
// We don't really need to test the entirety of download support
// since downloads is (almost) just another provider.
@Suppress
public void testDownload_Queued() throws Exception {
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
// This downloads ends up being queued (because DNS can't be resolved).
// We'll still see an entry in the downloads UI with a "Queued" label.
dm.enqueue(new Request(Uri.parse("http://hammychamp.toodles")));
bots.roots.openRoot("Downloads");
bots.directory.assertDocumentsPresent("Queued");
}
Aggregations