You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_method to uniquely identify our notification tap event
  • A PendingIntent wraps this custom intent, which gets triggered automatically when the user taps the notification
  • We register a dynamic BroadcastReceiver that listens for our custom action; when it receives the intent, it immediately calls your My_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 NotificationManager to display it to the user

内容的提问来源于stack exchange,提问作者canel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:35:55