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

时间:2014-04-23 06:28:48

标签: 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);

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

enter image description here

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

预期输出:

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

enter image description here

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

3 个答案:

答案 0 :(得分: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);

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

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();
        }
    }
}

enter image description here

答案 1 :(得分:3)

  

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

不直接。您的应用未显示{​​{1}};您无法控制它的行为。

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

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

答案 2 :(得分:-2)

在通知中添加RemoteView这是示例

RemoteViews remoteViews = new RemoteViews(getPackageName(),  
                     R.layout.widget);  
           NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(  
                     this).setSmallIcon(R.drawable.ic_launcher).setContent(  
                     remoteViews);  
           // Creates an explicit intent for an Activity in your app  
           Intent resultIntent = new Intent(this, test.class);  
           // The stack builder object will contain an artificial back stack for  
           // the  
           // started Activity.  
           // This ensures that navigating backward from the Activity leads out of  
           // your application to the Home screen.  
           TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);  
           // Adds the back stack for the Intent (but not the Intent itself)  
           stackBuilder.addParentStack(test.class);  
           // Adds the Intent that starts the Activity to the top of the stack  
           stackBuilder.addNextIntent(resultIntent);  
           PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,  
                     PendingIntent.FLAG_UPDATE_CURRENT);  
           remoteViews.setOnClickPendingIntent(R.id.button1, resultPendingIntent);  
           NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
           // mId allows you to update the notification later on.  
           mNotificationManager.notify(100, mBuilder.build()); 

widget.xml

<?xml version="1.0" encoding="UTF-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent"  
   android:gravity="center"  
   android:orientation="horizontal" >  
   <TextView  
     android:id="@+id/textView1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:gravity="center"  
     android:text="DJ notification"  
     android:textAppearance="?android:attr/textAppearanceMedium" />  
   <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Close Me" />  
 </LinearLayout> 

NotificationCompat.Builder是在所有Android版本上创建通知的最简单方法。您甚至可以使用Android 4.1提供的功能。如果您的应用在Android&gt; = 4.1的设备上运行,则会使用新功能,如果在Android&lt; 4.1上运行,通知将是一个简单的旧通知。

for&lt; 11 API使用http://www.framentos.com/en/android-tutorial/2012/02/20/how-to-create-a-custom-notification-on-android/