How to execute a method by clicking a notification

后端 未结 2 1988
渐次进展
渐次进展 2020-11-28 07:20

I have an application with two buttons. One button that \"closes\" the application and one that begins the algorithm. When I click \"begin\" it \"hides\" the application and

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 08:06

    On Notification click we can't get any fire event or any click listener. When we add notification in notification bar, we can set a pending intent, which fires an intent (activity/service/broadcast) upon notification click.

    I have a workound solution for you, if you really don't want to display your activity then the activity which is going to start with pending intent send a broad cast from there to your parent activity and just finish the pending activity and then once broadcast receiver receives in parent activity call whatever method you want inside the receiver. For your reference..

    // This is what you are going to set a pending intent which will start once
    // notification is clicked. Hopes you know how to add notification bar. 
    Intent notificationIntent = new Intent(this, dummy_activity.class);
    notificationIntent.setAction("android.intent.action.MAIN");
    notificationIntent.addCategory("android.intent.category.LAUNCHER");
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                                    notificationIntent,
                                    PendingIntent.FLAG_UPDATE_CURRENT | 
                                    Notification.FLAG_AUTO_CANCEL);
    
    // Now, once this dummy activity starts send a broad cast to your parent activity and finish the pending activity
    //(remember you need to register your broadcast action here to receive).
        BroadcastReceiver call_method = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action_name = intent.getAction();
                    if (action_name.equals("call_method")) {
                        // call your method here and do what ever you want.
                    }
                };
            };
            registerReceiver(call_method, new IntentFilter("call_method"));
        }
    }
    

提交回复
热议问题