当在 android 中在后台收到通知或消息时,有什么方法可以 运行 方法或意图吗?

Is there any way to run a method or intent when a notification or message is received in background in android?

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

收到通知后,如果您使用了通知监听器服务,您将收到通知

@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);
    }