Search in sources :

Example 11 with DownloadManager

use of android.app.DownloadManager in project XposedInstaller by rovo89.

the class DownloadsUtil method getById.

public static DownloadInfo getById(Context context, long id) {
    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = dm.query(new Query().setFilterById(id));
    if (!c.moveToFirst()) {
        c.close();
        return null;
    }
    int columnUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_URI);
    int columnTitle = c.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE);
    int columnLastMod = c.getColumnIndexOrThrow(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP);
    int columnFilename = c.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_FILENAME);
    int columnStatus = c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
    int columnTotalSize = c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
    int columnBytesDownloaded = c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
    int columnReason = c.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON);
    int status = c.getInt(columnStatus);
    String localFilename = c.getString(columnFilename);
    if (status == DownloadManager.STATUS_SUCCESSFUL && !new File(localFilename).isFile()) {
        dm.remove(id);
        c.close();
        return null;
    }
    DownloadInfo info = new DownloadInfo(id, c.getString(columnUri), c.getString(columnTitle), c.getLong(columnLastMod), localFilename, status, c.getInt(columnTotalSize), c.getInt(columnBytesDownloaded), c.getInt(columnReason));
    c.close();
    return info;
}
Also used : Query(android.app.DownloadManager.Query) Cursor(android.database.Cursor) DownloadManager(android.app.DownloadManager) File(java.io.File)

Example 12 with DownloadManager

use of android.app.DownloadManager in project XposedInstaller by rovo89.

the class DownloadsUtil method add.

private static DownloadInfo add(Builder b) {
    Context context = b.mContext;
    removeAllForUrl(context, b.mUrl);
    if (!b.mDialog) {
        synchronized (mCallbacks) {
            mCallbacks.put(b.mUrl, b.mCallback);
        }
    }
    String savePath = "XposedInstaller";
    if (b.mModule) {
        savePath = XposedApp.getDownloadPath().replace(Environment.getExternalStorageDirectory() + "", "");
    }
    Request request = new Request(Uri.parse(b.mUrl));
    request.setTitle(b.mTitle);
    request.setMimeType(b.mMimeType.toString());
    if (b.mDestination != null) {
        b.mDestination.getParentFile().mkdirs();
        removeAllForLocalFile(context, b.mDestination);
        request.setDestinationUri(Uri.fromFile(b.mDestination));
    } else if (b.mSave) {
        try {
            request.setDestinationInExternalPublicDir(savePath, b.mTitle + b.mMimeType.getExtension());
        } catch (IllegalStateException e) {
            Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    long id = dm.enqueue(request);
    if (b.mDialog) {
        showDownloadDialog(b, id);
    }
    return getById(context, id);
}
Also used : Context(android.content.Context) Request(android.app.DownloadManager.Request) DownloadManager(android.app.DownloadManager)

Example 13 with DownloadManager

use of android.app.DownloadManager in project kdeconnect-android by KDE.

the class SharePlugin method onPackageReceived.

@Override
public boolean onPackageReceived(NetworkPackage np) {
    try {
        if (np.hasPayload()) {
            Log.i("SharePlugin", "hasPayload");
            int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            } else if (permissionCheck == PackageManager.PERMISSION_DENIED) {
                // TODO Request Permission for storage
                Log.i("SharePlugin", "no Permission for Storage");
                return false;
            }
            final InputStream input = np.getPayload();
            final long fileLength = np.getPayloadSize();
            final String originalFilename = np.getString("filename", Long.toString(System.currentTimeMillis()));
            //We need to check for already existing files only when storing in the default path.
            //User-defined paths use the new Storage Access Framework that already handles this.
            final boolean customDestination = ShareSettingsActivity.isCustomDestinationEnabled(context);
            final String defaultPath = ShareSettingsActivity.getDefaultDestinationDirectory().getAbsolutePath();
            final String filename = customDestination ? originalFilename : FilesHelper.findNonExistingNameForNewFile(defaultPath, originalFilename);
            String displayName = FilesHelper.getFileNameWithoutExt(filename);
            final String mimeType = FilesHelper.getMimeTypeFromFile(filename);
            if ("*/*".equals(mimeType)) {
                displayName = filename;
            }
            final DocumentFile destinationFolderDocument = ShareSettingsActivity.getDestinationDirectory(context);
            final DocumentFile destinationDocument = destinationFolderDocument.createFile(mimeType, displayName);
            final OutputStream destinationOutput = context.getContentResolver().openOutputStream(destinationDocument.getUri());
            final Uri destinationUri = destinationDocument.getUri();
            final int notificationId = (int) System.currentTimeMillis();
            Resources res = context.getResources();
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setContentTitle(res.getString(R.string.incoming_file_title, device.getName())).setContentText(res.getString(R.string.incoming_file_text, filename)).setTicker(res.getString(R.string.incoming_file_title, device.getName())).setSmallIcon(android.R.drawable.stat_sys_download).setAutoCancel(true).setOngoing(true).setProgress(100, 0, true);
            final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build());
            new Thread(new Runnable() {

                @Override
                public void run() {
                    boolean successful = true;
                    try {
                        byte[] data = new byte[1024];
                        long progress = 0, prevProgressPercentage = 0;
                        int count;
                        while ((count = input.read(data)) >= 0) {
                            progress += count;
                            destinationOutput.write(data, 0, count);
                            if (fileLength > 0) {
                                if (progress >= fileLength)
                                    break;
                                long progressPercentage = (progress * 10 / fileLength);
                                if (progressPercentage != prevProgressPercentage) {
                                    prevProgressPercentage = progressPercentage;
                                    builder.setProgress(100, (int) progressPercentage * 10, false);
                                    NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build());
                                }
                            }
                        //else Log.e("SharePlugin", "Infinite loop? :D");
                        }
                        destinationOutput.flush();
                    } catch (Exception e) {
                        successful = false;
                        Log.e("SharePlugin", "Receiver thread exception");
                        e.printStackTrace();
                    } finally {
                        try {
                            destinationOutput.close();
                        } catch (Exception e) {
                        }
                        try {
                            input.close();
                        } catch (Exception e) {
                        }
                    }
                    try {
                        Log.i("SharePlugin", "Transfer finished: " + destinationUri.getPath());
                        //Update the notification and allow to open the file from it
                        Resources res = context.getResources();
                        String message = successful ? res.getString(R.string.received_file_title, device.getName()) : res.getString(R.string.received_file_fail_title, device.getName());
                        builder.setContentTitle(message).setTicker(message).setSmallIcon(android.R.drawable.stat_sys_download_done).setAutoCancel(true).setProgress(100, 100, false).setOngoing(false);
                        // TODO use FileProvider for >Nougat
                        if (Build.VERSION.SDK_INT < 24) {
                            if (successful) {
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setDataAndType(destinationUri, mimeType);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                                stackBuilder.addNextIntent(intent);
                                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                                builder.setContentText(res.getString(R.string.received_file_text, destinationDocument.getName())).setContentIntent(resultPendingIntent);
                            }
                        }
                        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                        if (prefs.getBoolean("share_notification_preference", true)) {
                            builder.setDefaults(Notification.DEFAULT_ALL);
                        }
                        NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build());
                        if (successful) {
                            if (!customDestination && Build.VERSION.SDK_INT >= 12) {
                                Log.i("SharePlugin", "Adding to downloads");
                                DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                                manager.addCompletedDownload(destinationUri.getLastPathSegment(), device.getName(), true, mimeType, destinationUri.getPath(), fileLength, false);
                            } else {
                                //Make sure it is added to the Android Gallery anyway
                                MediaStoreHelper.indexFile(context, destinationUri);
                            }
                        }
                    } catch (Exception e) {
                        Log.e("SharePlugin", "Receiver thread exception");
                        e.printStackTrace();
                    }
                }
            }).start();
        } else if (np.has("text")) {
            Log.i("SharePlugin", "hasText");
            String text = np.getString("text");
            if (Build.VERSION.SDK_INT >= 11) {
                ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setText(text);
            } else {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setText(text);
            }
            Toast.makeText(context, R.string.shareplugin_text_saved, Toast.LENGTH_LONG).show();
        } else if (np.has("url")) {
            String url = np.getString("url");
            Log.i("SharePlugin", "hasUrl: " + url);
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (openUrlsDirectly) {
                context.startActivity(browserIntent);
            } else {
                Resources res = context.getResources();
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                stackBuilder.addNextIntent(browserIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                Notification noti = new NotificationCompat.Builder(context).setContentTitle(res.getString(R.string.received_url_title, device.getName())).setContentText(res.getString(R.string.received_url_text, url)).setContentIntent(resultPendingIntent).setTicker(res.getString(R.string.received_url_title, device.getName())).setSmallIcon(R.drawable.ic_notification).setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).build();
                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                NotificationHelper.notifyCompat(notificationManager, (int) System.currentTimeMillis(), noti);
            }
        } else {
            Log.e("SharePlugin", "Error: Nothing attached!");
        }
    } catch (Exception e) {
        Log.e("SharePlugin", "Exception");
        e.printStackTrace();
    }
    return true;
}
Also used : OutputStream(java.io.OutputStream) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) Uri(android.net.Uri) DownloadManager(android.app.DownloadManager) Notification(android.app.Notification) NotificationCompat(android.support.v4.app.NotificationCompat) Context(android.content.Context) ClipboardManager(android.content.ClipboardManager) DocumentFile(android.support.v4.provider.DocumentFile) NotificationManager(android.app.NotificationManager) SharedPreferences(android.content.SharedPreferences) InputStream(java.io.InputStream) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Resources(android.content.res.Resources) PendingIntent(android.app.PendingIntent) TaskStackBuilder(android.support.v4.app.TaskStackBuilder)

Example 14 with DownloadManager

use of android.app.DownloadManager in project mobile-center-sdk-android by Microsoft.

the class DownloadTask method doInBackground.

@Override
protected Void doInBackground(Void[] params) {
    /* Download file. */
    Uri downloadUrl = mReleaseDetails.getDownloadUrl();
    MobileCenterLog.debug(LOG_TAG, "Start downloading new release, url=" + downloadUrl);
    DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(downloadUrl);
    /* Hide mandatory download to prevent canceling via notification cancel or download U.I. delete. */
    if (mReleaseDetails.isMandatoryUpdate()) {
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        request.setVisibleInDownloadsUi(false);
    }
    long enqueueTime = System.currentTimeMillis();
    long downloadRequestId = downloadManager.enqueue(request);
    Distribute.getInstance().storeDownloadRequestId(downloadManager, this, downloadRequestId, enqueueTime);
    return null;
}
Also used : Uri(android.net.Uri) DownloadManager(android.app.DownloadManager)

Example 15 with DownloadManager

use of android.app.DownloadManager in project android_frameworks_base by ResurrectionRemix.

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");
}
Also used : Request(android.app.DownloadManager.Request) DownloadManager(android.app.DownloadManager) Suppress(android.test.suitebuilder.annotation.Suppress)

Aggregations

DownloadManager (android.app.DownloadManager)53 File (java.io.File)14 Cursor (android.database.Cursor)13 Request (android.app.DownloadManager.Request)12 Uri (android.net.Uri)12 Suppress (android.test.suitebuilder.annotation.Suppress)10 Query (android.app.DownloadManager.Query)9 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 Intent (android.content.Intent)5 UiObject (android.support.test.uiautomator.UiObject)5 Response (com.android.volley.Response)3 Context (android.content.Context)2 Nullable (android.support.annotation.Nullable)2 AlertDialog (android.support.v7.app.AlertDialog)2 View (android.view.View)2 Request (com.android.volley.Request)2 VolleyError (com.android.volley.VolleyError)2 FileInputStream (java.io.FileInputStream)2 JSONObject (org.json.JSONObject)2