Event OnClick for a button in a custom notification

后端 未结 5 1612
再見小時候
再見小時候 2020-11-27 15:53

I have a custom notification with a button. To set the notification and use the event OnClick on my button I\'ve used this code:

//Notification and intent of         


        
5条回答
  •  星月不相逢
    2020-11-27 16:33

    I am writing code in my MyActivity.java class that extends android.app.Activity

    It creates a custom notification, when user click on the button it sends a broadcast. There is a broadcast receiver that receives the broadcast.

    private void createDownloadNotification() {
            Intent closeButton = new Intent("Download_Cancelled");
            closeButton.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    
            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, closeButton, 0);
    
            RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.widget_update_notification);
    
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setTicker("Ticker Text").setContent(notificationView);
            notificationView.setProgressBar(R.id.pb_progress, 100, 12, false);
            notificationView.setOnClickPendingIntent(R.id.btn_close, pendingSwitchIntent);
    
            notificationManager.notify(1, builder.build());
    
        }
    
    
    public static class DownloadCancelReceiver extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) {
    
                System.out.println("Received Cancelled Event");
            }
        }
    

    Register receiver in AndroidManifest.xml

    
                
                    
                
            
    

    Since it is inner class so have to use $ sign

    Widget xml is here

    
    
    
        

提交回复
热议问题