Android如何实现发送通知并点击时触发指定函数?
Solution: Trigger a Function When Tapping a Notification (No Manifest Changes)
Hey folks, if you're looking to send a notification that runs My_Function(mytext) when tapped, this solution from Diego D is exactly what you need—no need to modify your AndroidManifest at all. We'll use a dynamic BroadcastReceiver to handle the tap action seamlessly.
Here's the full implementation code:
public void Notification(final String mytext) { final Intent notifIntent = new Intent("action_call_method"); PendingIntent pendingmyIntent = PendingIntent.getBroadcast(context, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("action_call_method")) { My_Function(mytext); } } }; IntentFilter filter = new IntentFilter("action_call_method"); context.registerReceiver(receiver, filter); Notification noti = new Notification.Builder(context) .setTicker(ticker) .setContentTitle(title) .setContentText(text) .setSmallIcon(R.drawable.ic_lock_silent_mode_off) .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.FLAG_SHOW_LIGHTS) .setAutoCancel(true) .setContentIntent(pendingmyIntent) .build(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, noti); }
Quick breakdown of how this works:
- We create a custom intent with the action
action_call_methodto uniquely identify our notification tap event - A
PendingIntentwraps this custom intent, which gets triggered automatically when the user taps the notification - We register a dynamic
BroadcastReceiverthat listens for our custom action; when it receives the intent, it immediately calls yourMy_Function(mytext)with the provided parameter - The notification is configured with standard alert behaviors (vibration, sound, lights) and set to auto-cancel once tapped
- Finally, we pass the built notification to the
NotificationManagerto display it to the user
内容的提问来源于stack exchange,提问作者canel
相关产品推荐
相关产品推荐

