如何添加暂停和取消按钮到自定义下载通知android

时间:2018-03-18 05:03:04

标签: android notifications

我已经为从给定网址下载mp3文件创建了自定义通知。但我需要知道如何将pausecancel按钮添加到我创建的自定义通知中。

以下是自定义通知的部分代码:

 if (!downloadUrl.toString().isEmpty()) {
                                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
                                    request.setMimeType("audio/MP3");
                                    request.setTitle(vMeta.getTitle());
                                    request.allowScanningByMediaScanner();
                                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
                                    request.setDestinationInExternalPublicDir(storage, vMeta.getTitle() + extension);
                                    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

                                    final long id = manager.enqueue(request);


                                    registerReceiver(new DownloadReceiver(id, storage, vMeta.getTitle() + extension),
                                            new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                                    mBuilder =  new NotificationCompat.Builder(getApplicationContext());
                                    Intent intent = new Intent();
                                    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
                                    mBuilder.setContentIntent(pendingIntent);
                                    mBuilder.setSmallIcon(R.drawable.ic_music_video_white_24dp);
                                    mBuilder.setContentTitle("Downloading");
                                    mBuilder.setContentText(vMeta.getTitle());
                                    mBuilder.setOngoing(false);
                                    //mBuilder.addAction();
                                    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {

                                            boolean downloading = true;

                                            while (downloading) {
                                                DownloadManager.Query q = new DownloadManager.Query();
                                                q.setFilterById(id);
                                                Cursor cursor = manager.query(q);
                                                cursor.moveToFirst();
                                                if( cursor != null && cursor.moveToFirst() ) {
                                                    bytes_downloaded = cursor.getInt(cursor
                                                            .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                                                    bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                                                    dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
                                                }
                                                mNotificationManager.notify(001, mBuilder.build());
                                                if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                                                    downloading = false;
                                                    mBuilder.setContentTitle("Download complete")
                                                            .setOngoing(false)
                                                            .setAutoCancel(true)
                                                            .setProgress(100,100,false);
                                                    mNotificationManager.notify(001, mBuilder.build());
                                                }


                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        mBuilder.setContentTitle("Downloading: "+dl_progress+"%");
                                                        mBuilder.setProgress(100,dl_progress,false);
                                                        mNotificationManager.notify(001, mBuilder.build());

                                                    }
                                                });

                                                cursor.close();
                                            }

                                        }
                                    }).start();



                                }
                            }
                        }
                    }.extract(ytLink, true, true);
                }
            });
        }
    }
    protected void onDestroy() {

        super.onDestroy();
    }
    public void onBackPressed(){
        super.onBackPressed();
    }

    public class DownloadReceiver extends BroadcastReceiver {
        private long id;
        private String dirType;
        private String subPath;

        public DownloadReceiver(long id, String dirType, String subPath) {
            this.id = id;
            this.dirType = dirType;
            this.subPath = subPath;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) == id) {
                MainActivity.this.unregisterReceiver(this);
                File oldFile = new File(Environment.getExternalStoragePublicDirectory(dirType), subPath);
                String newSubPath = subPath.substring(0, subPath.lastIndexOf('.')) +"|MEGA"+".mp3";
                File newFile = new File(Environment.getExternalStoragePublicDirectory(dirType), newSubPath);
                Boolean result = oldFile.renameTo(newFile);
                Toast.makeText(context, "Download " + (result ? "succeeded" : "failed"), Toast.LENGTH_SHORT).show();
            }
        }
    }

2 个答案:

答案 0 :(得分:3)

您需要将特定操作设置为具有媒体控制的通知,您可以添加具有相对未决意图的特定操作

.addAction(R.drawable.ic_prev, "Previous", prevPendingIntent) 
.addAction(R.drawable.ic_pause, "Pause", pausePendingIntent) 
.addAction(R.drawable.ic_next, "Next", nextPendingIntent) 

您还需要使用以下代码设置媒体样式

 .setStyle(MediaNotificationCompat.MediaStyle()
 .setShowActionsInCompactView(1 /* #1: pause button \*/)
 .setMediaSession(mMediaSession.getSessionToken()))

您也可以查看this link了解更多说明。

答案 1 :(得分:2)

请参考一个简单的示例,所有内容都在代码中:

public class MainActivity extends AppCompatActivity {
    private DownloadReceiver downloadReceiver = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();

        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                notifyFirst();
                notifySecondNotification();
            }
        });
    }

    private void init() {
        downloadReceiver = new DownloadReceiver();
        IntentFilter intentFilter = new IntentFilter(DownloadReceiver.ACTION_1);
        intentFilter.addAction(DownloadReceiver.ACTION_2);
        registerReceiver(downloadReceiver, intentFilter);
    }


    private void notifySecondNotification() {

        Intent button1I = new Intent(DownloadReceiver.ACTION_1);
        PendingIntent button1PI = PendingIntent.getBroadcast(this, 0, button1I, 0);

        Intent button2I = new Intent(DownloadReceiver.ACTION_2);
        PendingIntent button2PI = PendingIntent.getBroadcast(this, 0, button2I, 0);
        /*
         * use RemoteViews to custom notification layout
         * R.layout.notification
         */
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification);
        /*
         * bind click event
         */
        remoteViews.setOnClickPendingIntent(R.id.notificationButton1, button1PI);
        remoteViews.setOnClickPendingIntent(R.id.notificatinoButton2, button2PI);

        Notification notification = new NotificationCompat.Builder(this)
                .setTicker("tttttttttt")
                .setContentTitle("setContentTitle")
                .setContentText("setContentText")
                .setSmallIcon(android.R.drawable.ic_menu_report_image)
                /**
                 * set remoteViews
                 */
                .setContent(remoteViews)
                .build();

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(0, notification);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(downloadReceiver); 
    }
}

您的下载接收器示例:

public class DownloadReceiver extends BroadcastReceiver {
    public static final String ACTION_1 = "Press11111";
    public static final String ACTION_2 = "Press22222";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        assert action != null;
        String toastStr = "you touch";
        if (action.equals(ACTION_1)) {
            //download......
            Toast.makeText(context, toastStr + "1111111", Toast.LENGTH_SHORT).show();
        } else if (action.equals(ACTION_2)) {
           //cancle download......
            Toast.makeText(context, toastStr + "2222222", Toast.LENGTH_SHORT).show();
        }
    }

}

notification.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/notificationLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFAADD"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/notificationButton1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/abdroid" />
    <Button
        android:id="@+id/notificatinoButton2"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/abdroid"/>

</LinearLayout>