Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/213.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 颤振-用户打开push notif消息(FCM)后如何执行任务_Android_Firebase_Flutter_Dart_Google Cloud Functions - Fatal编程技术网

Android 颤振-用户打开push notif消息(FCM)后如何执行任务

Android 颤振-用户打开push notif消息(FCM)后如何执行任务,android,firebase,flutter,dart,google-cloud-functions,Android,Firebase,Flutter,Dart,Google Cloud Functions,我有firebase云消息(FCM),可以向我的用户发送消息 但是,我想做一个场景,如果我的用户点击他们手机上的通知消息,那么应用程序将打开一个视图或弹出窗口,并执行一些后台任务 这可能吗 多谢各位 ==根据Shady Boshra的建议更新问题 1) 我使用typeScript创建谷歌云函数的firebase: import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; ad

我有
firebase云消息(FCM)
,可以向我的用户发送消息

但是,我想做一个场景,如果我的用户点击他们手机上的通知消息,那么应用程序将打开一个视图或弹出窗口,并执行一些后台任务

这可能吗

多谢各位

==根据Shady Boshra的建议更新问题

1) 我使用
typeScript
创建谷歌云函数的firebase:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
const fcm = admin.messaging();

export const sendNotif = functions.https.onRequest((request, response) => {

   const tokens = request.query.tokens;
   const payload: admin.messaging.MessagingPayload = {
   notification: {
      title: '[TEST-123] title...',
      body: `[TEST-123]  body of message... `,          
      click_action: 'FLUTTER_NOTIFICATION_CLICK',
      tag: "news",
      data: "{ picture: 'https://i.imgur.com/bY2bBGN.jpg', link: 'https://example.com' }"
    }
  };
  const res = fcm.sendToDevice(tokens, payload);
  response.send(res);
});
2) 我更新我的移动应用程序代码/Dart

_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) {
  print("::==>onMessage: $message");

  message.forEach((k,v) => print("${k} - ${v}"));

  String link = "https://example.com";

  FlutterWebBrowser.openWebPage(url: link, androidToolbarColor: Pigment.fromString(UIData.primaryColor));
  return null;
},
==更新3(对Shady Boshra回答的回应)

下面是我关于颤振的代码:

  _firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) {
  print("::==>onMessage: $message");

  message.forEach((k,v) => print("${k} - ${v}"));

  var data = message['notification']['data']['link'];
  print ("===>data_notif = "+data.toString());

  var data2 = message['data']['link'];
  print ("===>data_notif2 = "+data2.toString());
...
\u firebaseMessaging.configure(
onMessage:(映射消息){
打印(“::==>onMessage:$message”);
message.forEach((k,v)=>print(${k}-${v}”);
var data=消息['notification']['data']['link'];
打印(“=>data_notif=“+data.toString());
var data2=消息['data']['link'];
打印(“=>data_notif2=“+data2.toString());
...
在发送push notif后,我在调试中刚刚收到以下消息:

The application is paused.
Reloaded 22 of 1277 libraries.
I/flutter (18608): 0
I/flutter (18608): AsyncSnapshot<String>(ConnectionState.active, Tuesday, September 3, 2019, null)
I/flutter (18608): ::==>onMessage: {notification: {body: [TEST-123]  body of message... , title: [TEST-123] title...}, data: {}}
I/flutter (18608): notification - {body: [TEST-123]  body of message... , title: [TEST-123] title...}
I/flutter (18608): data - {}
Application finished.
应用程序已暂停。
重新加载了1277个库中的22个。
I/颤振(18608):0
I/颤振(18608):异步快照(ConnectionState.active,2019年9月3日星期二,空)
I/flatter(18608)::=>onMessage:{notification:{body:[TEST-123]消息体…,title:[TEST-123]title…},数据:{}
I/flatter(18608):通知-{body:[TEST-123]消息体…,title:[TEST-123]title…}
I/颤振(18608):数据-{}
申请完成。

如您所见,我无法获得
链接
内部
数据

的值,是的,在本机中可以,但在flifter中我不确定。 你可以建造一个带有后堆叠的悬挂式帐篷

Intent notifIntent = new Intent(this, notifActivity.class);
TaskStackBuilder stkBuilder = TaskStackBuilder.create(this);
stkBuilder.addNextIntentWithParentStack(notifIntent);
PendingIntent resultPendingIntent =
        stkBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
然后您应该将挂起的内容传递给通知

检查此链接:

当然,你也可以在颤振上做

首先,我希望您在清单中设置这些代码


在后端(node.js)的JSON通知正文中添加标记元素

const payload: admin.messaging.MessagingPayload = {
  notification: {
    title: 'New Puppy!',
    body: `${puppy.name} is ready for adoption`,
    icon: 'your-icon-url',
    tag: 'puppy', 
    data: {"click_action": "FLUTTER_NOTIFICATION_CLICK", "id": "1", "status": "done"}, 
    click_action: 'FLUTTER_NOTIFICATION_CLICK' // required only for onResume or onLaunch callbacks
  }
};
在Dart代码中,确保在第一个initState()页面中设置此代码

•数据消息-包含键/值对形式的数据,并且 直接交付到应用程序而不触发通知 数据消息用于以静默方式向应用程序发送数据

例:

var payload = {
  notification: {
    title: "Account Deposit",
    body: "A deposit to your savings account has just cleared."
  }
};
var payload = {
  data: {
    account: "Savings",
    balance: "$3020.25"
  }
};
var payload = {
  notification: {
    title: "Account Deposit",
    body: "A deposit to your savings account has just cleared."
  },
  data: {
    account: "Savings",
    balance: "$3020.25"
  }
};
•组合消息–包含包含两个通知的有效负载 和数据。通知将显示给用户,并且数据 发送到应用程序

例:

var payload = {
  notification: {
    title: "Account Deposit",
    body: "A deposit to your savings account has just cleared."
  }
};
var payload = {
  data: {
    account: "Savings",
    balance: "$3020.25"
  }
};
var payload = {
  notification: {
    title: "Account Deposit",
    body: "A deposit to your savings account has just cleared."
  },
  data: {
    account: "Savings",
    balance: "$3020.25"
  }
};
因此,我认为您将使用第三个,它同时发送通知和数据

您可以使用dart访问数据,如下所示

message['data']['account']
更新2 当你更新你的问题时,我的解决方案没有很好地与你配合。我决定自己测试它,猜猜看!它与你的和相同的代码配合得很好

My node.js后端代码

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.firestore();
const fcm = admin.messaging();

exports.sendNotification = functions.firestore
    .document('orders/{orderId}')
    .onCreate(async snapshot => {

        const order = snapshot.data();

        // Token of my device only
        const tokens = ["f5zebdRcsgg:APA91bGolg9-FiLlCd7I0LntNo1_7b3CS5EAJBINZqIpaz0LVZtLeGCvoYvfjQDhW0Qdt99jHHS5r5mXL5Up0kBt2M7rDmXQEqVl_gIpSQphbaL2NhULVv3ZkPXAY-oxX5ooJZ40TQ2-"];

        const payload = {
            notification: {
                title: "Account Deposit",
                body: "A deposit to your savings account has just cleared."
            },
            data: {
                account: "Savings",
                balance: "$3020.25",
                link: "https://somelink.com"
            }
        };

        return fcm.sendToDevice(tokens, payload);
    });
和省道代码

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    super.initState();

    _firebaseMessaging.requestNotificationPermissions();

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");

        var data2 = message['data']['link'];
        print ("===>data_notif2 = "+data2.toString());

        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            content: ListTile(
              title: Text(message['notification']['title']),
              subtitle: Text(message['notification']['body']),
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('Ok'),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          ),
        );
      },
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
        // TODO optional
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
        // TODO optional
      },
    );

    _saveDeviceToken();
  }

  /// Get the token, save it to the database for current user
  _saveDeviceToken() async {
    // Get the current user
    String uid = 'jeffd23';
    // FirebaseUser user = await _auth.currentUser();

    // Get the token for this device
    String fcmToken = await _firebaseMessaging.getToken();

    // Save it to Firestore
    if (fcmToken != null) {
      print(fcmToken);
    }
  }

因此,我相信问题出在您的代码中,而不是我给您的解决方案中。请清楚地查找您可能遇到的问题。希望您能找到它并为您工作。

最简单的方法是,如果您没有足够的时间构建后端以发送推送通知,那么如果使用firebase,OneSignal对n其订户(免费至30000订户).

我尝试了您的解决方案,但仍然没有使用
nodejs
而是使用firebase控制台。我收到了关于
onMessage
状态的消息,但是对于
onLaunch
onResume
我无法在调试控制台上获得它。有什么想法吗?我更新了我的答案,请重新阅读,但您将无法继续使用firebase co仅限NSLE,然后应继续使用后端node.js作为示例。我的Android清单上已有
flatter\u NOTIFICATION\u CLICK
intent。但它不起作用…现在可以解决了,因为我以前的代码(firebase)正在使用
typeScript
而不是
javascript
哦,我明白了。祝你完美的时间编码。尝试删除双qoutes,看看它是否有效,
数据:{picture:'https://i.imgur.com/bY2bBGN.jpg'链接:'https://example.com“}
@ShadyBoshra如果我这样做,它会返回错误,请参阅更新的问题(更新2)…试试这个
数据:{'picture':'https://i.imgur.com/bY2bBGN.jpg'链接':'https://example.com“}
我在keystil错误前后添加了单个qoute:
类型“{'picture':string;'link':string;}”不能分配给类型“string”。
@ShadyBoshra对不起,还没有。我明天再看。谢谢。。。。