Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add pause and cancel button to custom download notification android

I have created a custom notification for Downloading an mp3 file from a given URL. But I need to know how to add pause and cancel button to the custom notification I created.

Here is the partial code for custom Notification :

 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();
            }
        }
    }
like image 529
PSN Avatar asked Mar 18 '18 05:03

PSN


2 Answers

You need to set particular action to notification with media control you can add particular action with relative pending intent

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

You also need to set media style using below code

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

You can also check this link for more instructions.

like image 71
karan Avatar answered Nov 12 '22 04:11

karan


Refer to a simple example,everything is in the code:

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

your download receiver example:

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>
like image 35
Tang HuaiZhe Avatar answered Nov 12 '22 05:11

Tang HuaiZhe