启动通知,当点击它时,运行其他功能
Posted
技术标签:
【中文标题】启动通知,当点击它时,运行其他功能【英文标题】:Launch a Notification and when tap on it, run other function 【发布时间】:2018-06-16 08:49:14 【问题描述】:解决了。这个问题由 Diego D 解决。
此代码通过函数启动通知:Notification(final String mytext)。 我们收到带有代码、标题、文本、自动取消的通知...当点击它时,运行其他功能:My_Function(mytext);
为了工作,它不需要修改 androidManifest,因为使用了广播。
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);
【问题讨论】:
How to set click listener for notification?的可能重复 这不是重复的,因为在这篇文章中需要在同一个类文件中运行其他函数并且不使用 AndroidManifest @canel 不客气!顺便说一句,我刚刚重命名了自己,因为那是一个非常古老的堆栈帐户哈哈。 -以前是 Theodore M. 【参考方案1】:在您的PendingIntent
中为Intent
设置自定义操作并向其注册接收器,然后您就可以为所欲为:
Intent notifIntent = new Intent("action_call_method");
PendingIntent pendingmyIntent = PendingIntent.getActivity(context, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
然后注册一个BroadcastReceiver
BroadcastReceiver receiver = new BroadcastReceiver()
@Override
public void onReceive(Context context, Intent intent)
if (intent.getAction().equals("action_call_method"))
// Call your method here
;
IntentFilter filter = new IntentFilter("action_call_method");
registerReceiver(receiver, filter);
不要忘记取消注册您的接收器。
【讨论】:
以上是关于启动通知,当点击它时,运行其他功能的主要内容,如果未能解决你的问题,请参考以下文章
iOS,先强制退出应用,点击接收通知banner后,应用启动失败