我们可以为android.os.DownloadManager提供自定义通知吗?

Vik*_*ngh 7 android android-notifications android-download-manager

目前我使用下面的代码片段来下载文件DownloadManager:

String servicestring = Context.DOWNLOAD_SERVICE;
                DownloadManager downloadmanager;
                downloadmanager = (DownloadManager) getSystemService(servicestring);
                Uri uri = Uri
                        .parse("some url here");
                DownloadManager.Request request = new Request(uri);
Run Code Online (Sandbox Code Playgroud)

使用此代码我收到以下通知.

在此输入图像描述

我的问题是,我们可以在此通知中添加一些交叉按钮,以便如果用户单击该按钮它将取消下载吗?

预期产量:

(单击此红叉图标时,用户必须能够取消下载)

在此输入图像描述

如果有的话,请提出一些建议.谢谢

Sha*_*sul 5

我正在使用NotificationManager显示下载百分比和取消按钮。

创建待处理的意图以处理“取消”按钮单击事件。

mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getApplicationContext());
mBuilder.setContentTitle("Extracting link")
         .setContentText("Please wait")
         .setSmallIcon(R.drawable.notification_icon_new)
         .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
         .setColor(getResources().getColor(R.color.colorAccent))
         .setSound(defaultSoundUri)
         .addAction(R.drawable.ic_pause_circle_filled_black_24dp, "Pause", pendingIntentPause)
         .addAction(R.drawable.ic_cancel_black_24dp, "Cancel", pendingIntentCancel)
         .setContentIntent(pendingIntent)
         .setCategory(NotificationCompat.CATEGORY_MESSAGE)
         .setProgress(0, 0, true);
    mNotifyManager.notify(randomNumber, mBuilder.build()); 

Looper mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
initDownload(urlString, randomNumber, mServiceHandler);
Run Code Online (Sandbox Code Playgroud)

下载逻辑并更新通知进度。

private void initDownload(String downloadUrl, int notificationId, ServiceHandler mServiceHandler) {
        try {

            URL url = new URL(downloadUrl);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();
            String fileExtension = MimeTypeMap.getFileExtensionFromUrl(downloadUrl);
            fileName = System.currentTimeMillis() + "." + fileExtension;

            // download the file
            InputStream input = new BufferedInputStream(connection.getInputStream());
            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/" + AppConstant.APP_FOLDER_NAME + "/" + fileName);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            int previousProgress = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                int progress = (int) (total * 100 / fileLength);
                output.write(data, 0, count);
                if (progress == 100 || progress > previousProgress + 4) {
                    // Only post progress event if we've made progress.
                    previousProgress = progress;
                    Message msg = mServiceHandler.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putInt("ID", notificationId);
                    bundle.putInt("PROGRESS", progress);
                    msg.setData(bundle);
                    mServiceHandler.sendMessage(msg);
                }
            }
            output.flush();
            output.close();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

private final class ServiceHandler extends Handler {

    ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        try {
            int mNotificationId = msg.getData().getInt("ID");
            int mProgress = msg.getData().getInt("PROGRESS");
            if (mProgress == -1) {
                mBuilder.setContentTitle("Download fail")
                        .setContentText("Try another one")
                        .setAutoCancel(true)
                        .setOngoing(false)
                        .setProgress(0, 0, false);
            } else {
                mBuilder.setContentTitle("Downloading...")
                        .setContentText(mProgress + " % downloaded")
                        .setProgress(100, mProgress, false);
                if (mProgress == 100) {
                    mBuilder.setContentTitle(fileName)
                            .setContentText("Download complete, Tap to view")
                            .setAutoCancel(true)
                            .setOngoing(false)
                            .setProgress(0, 0, false);
                }
            }
            mNotifyManager.notify(mNotificationId, mBuilder.build());

        } catch (Exception e) {
            Log.d("shams", " Exception--->  " + e);
            HashMap<String, String> parameters11 = new HashMap<>();
            parameters11.put("error_message", e.getMessage());
            FlurryAgent.logEvent("video_download_fail_exception", parameters11);
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Com*_*are 3

我们可以在此通知中添加一些十字按钮,以便如果用户单击该按钮它将取消下载吗?

不直接。Notification您的应用程序不会显示该信息;你无法控制它的行为。

最可能的解决方案是不使用DownloadManager,而是自己下载内容。然后,您可以将您想要的任何内容显示为Notification.

中间立场是使用DownloadManager但设置标志和权限以允许您请求不显示Notification. 然后,您就可以拥有自己的Notification. 这里的缺点是您可能无法重现系统提供的所有功能Notification(例如,完成百分比进度指示器)。