【问题标题】:Is there any way to run a method or intent when a notification or message is received in background in android?当在android的后台收到通知或消息时,有什么方法可以运行方法或意图?
【发布时间】:2018-03-30 05:05:53
【问题描述】:

我正在开发一个应用程序,当从另一台设备接收到消息或通知时,我想在该应用程序上运行一个方法。 通知或方法将从发送方设备发送,方法应在接收方设备上运行。 请指导我。提前致谢

【问题讨论】:

  • 您需要使用 Notification Listener Service 来监听通知。并检查通知是否适用于您的应用,然后调用方法
  • 谢谢,但请您详细说明一下吗?
  • 我不想在点击通知时调用方法。我想在收到通知时在后台调用方法。有什么办法吗?
  • NotificationListenerService 是一项服务,并且有一个方法 onNotificationPosted() 将在收到通知时调用

标签: android firebase push-notification message


【解决方案1】:

收到通知后,如果您使用了Notification Listener Service

,将会收到通知
@TargetApi(18)
public class NotificationsListenerService extends android.service.notification.NotificationListenerService {



    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    @Override
    public void onListenerConnected() {

        Log.d("NotificationListener", "listenerconnected");
    }


    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
      //here check notification and call method


    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.d("NotificationListener","removed "+ sbn.getPackageName() + " notification");
    }

要使用此服务,您需要通知权限

        String enabledNotificationListeners = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners");
        String packageName = getPackageName();
        if (enabledNotificationListeners == null || !enabledNotificationListeners.contains(packageName)) {
               startActivityForResult(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"), 13);
               Toast.makeText(getApplicationContext(),"Turn on Notification Access for \"App\"",Toast.LENGTH_SHORT).show();

    } else {
        startService(this, NotificationsListenerService.class);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多