这是我的舱单:
<service android:name=".fcm.PshycoFirebaseMessagingServices">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".fcm.PshycoFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
当应用程序在后台和通知到达,然后默认通知来,不运行我的onmessagerreceived代码。
这是我的onMessageReceived代码。如果我的应用程序在前台运行,而不是在后台运行,就会调用这个函数。我怎么能运行这段代码时,应用程序是在后台太?
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
data = remoteMessage.getData();
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
String imageUrl = (String) data.get("image");
String action = (String) data.get("action");
Log.i(TAG, "onMessageReceived: title : "+title);
Log.i(TAG, "onMessageReceived: message : "+message);
Log.i(TAG, "onMessageReceived: imageUrl : "+imageUrl);
Log.i(TAG, "onMessageReceived: action : "+action);
if (imageUrl == null) {
sendNotification(title,message,action);
} else {
new BigPictureNotification(this,title,message,imageUrl,action);
}
}
// [END receive_message]
根据OAUTH 2.0:
由于FCM现在使用OAUTH 2,在这种情况下将会有认证问题
所以我阅读了firebase文档,并根据文档发布数据消息的新方法是;
POST: https://fcm.googleapis.com/v1/projects/YOUR_FIREBASEDB_ID/messages:send
头
Key: Content-Type, Value: application/json
Auth
Bearer YOUR_TOKEN
例子的身体
{
"message":{
"topic" : "xxx",
"data" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message"
}
}
}
在url中有数据库Id,你可以在你的firebase控制台上找到它。(Go项目设置)
现在让我们用我们的代币(它只有效1小时):
首先在Firebase控制台中,打开设置>服务帐户。单击“生成新的私钥”,安全存储包含该私钥的JSON文件。我需要这个JSON文件来手动授权服务器请求。我下载了。
然后我创建了一个node.js项目,并使用这个函数来获得我的令牌;
var PROJECT_ID = 'YOUR_PROJECT_ID';
var HOST = 'fcm.googleapis.com';
var PATH = '/v1/projects/' + PROJECT_ID + '/messages:send';
var MESSAGING_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
var SCOPES = [MESSAGING_SCOPE];
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
getAccessToken().then(function(accessToken) {
console.log("TOKEN: "+accessToken)
})
});
function getAccessToken() {
return new Promise(function(resolve, reject) {
var key = require('./YOUR_DOWNLOADED_JSON_FILE.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
null
);
jwtClient.authorize(function(err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
现在我可以在我的post请求中使用这个令牌。然后我发布我的数据消息,它现在由我的应用程序onmessagerecreceived函数处理。
在一般情况下
FCM (Firebase Cloud Messaging)中有两种类型的消息:
显示消息:这些消息仅在应用程序处于前台时触发onmessagerreceived()回调
数据消息:这些消息触发onmessagerreceived()回调,即使你的应用程序在前台/后台/被杀死
数据电文示例:
{
"to": "/path",
"data":
{
"my_custom_key": "my_custom_value",
"my_custom_key2": true
}
}
显示消息示例:
{
"notification": {
"title" : "title",
"body" : "body text",
"icon" : "ic_notification",
"click_action" : "OPEN_ACTIVITY_1"
}
}
Android端可以处理如下通知:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
…
@Override public void onMessageReceived(RemoteMessage remoteMessage){
Map<String, String> data = remoteMessage.getData();
String myCustomKey = data.get("my_custom_key");
}
…
}
更多关于FCM的详细信息可以在这里找到:在Android上设置一个Firebase云消息客户端应用程序
我想出了各种方案
当app在前台时,
onMessageReceived()方法从FirebaseService调用。因此,服务类中定义的pendingIntent将被调用。
当app在后台时,第一个activity被调用。
现在,如果你使用了一个splashactivity,那么必须记住splashactivity会被调用,否则如果没有splashactivity,那么无论第一个activity是什么,都会被调用。
然后你需要检查firstActivity的getIntent(),看看它是否有任何bundle。如果一切正常,你会看到bundle在那里,值被填充。如果从服务器发送的数据标签中的值是这样的,
"data": {
"user_name": "arefin sajib",
"value": "user name notification"
}
然后在第一个活动中,你会看到,
有一个有效的意图(getIntent()不是null),有效的捆绑包和在捆绑包内,会有上面提到的以数据为键的整个JSON。
在这种情况下,提取值的代码是这样的,
if(getIntent()!=null){
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
try {
JSONObject object = new JSONObject(bundle.getStringExtra("data"));
String user_name = object.optString("user_name");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
为了能够从应用程序在后台发送的firebase通知中检索数据,您需要在通知数据集中添加click_action条目。
在firebase控制台设置额外的通知选项,如下所示:(你必须包括你想在应用程序中检索的任何额外数据):
并包括意图过滤器在你的manifest文件下的活动要启动
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.MyApp.SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<intent-filter>
<action android:name="FIREBASE_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
然后在你的onNewIntent活动中获取bundle数据:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Bundle data = intent.getExtras();
if (data != null) {
for (String key : data.keySet()) {
Object value = data.get(key);
// do what you want with the data entries
Log.d(FIREBASE_TAG, "Key: " + key + " Value: " + value);
Toast.makeText(this, "Key: "+key+".... Value: "+value, Toast.LENGTH_LONG).show;
}
}
}
当你的应用程序在前台时,你可以像这样设置onmessagerecreceived:
@Override
public void onMessageReceived(@NonNull RemoteMessage message) {
Log.d(FIREBASE_TAG, "Message From: " + message.getFrom());
if (message.getNotification() != null) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Map<String, String> data = message.getData();
if(data != null && !data.isEmpty()){
for(Map.Entry<String ,String > entry : data.entrySet()) {
intent.putExtra(entry.getKey(), entry.getValue());
}
}
//.......
// implement the rest of the code to show notification
//
}
}
根据文件
Handle messages in a backgrounded app
When your app is in the background, Android directs notification
messages to the system tray. A user tap on the notification opens the
app launcher by default.
This includes messages that contain both notification and data
payload. In these cases, the notification is delivered to the device's
system tray, and the data payload is delivered in the extras of the
intent of your launcher Activity.
If you want to open your app and perform a specific action, set
click_action in the notification payload and map it to an intent
filter in the Activity you want to launch. For example, set
click_action to OPEN_ACTIVITY_1 to trigger an intent filter like the
following:
<intent-filter> <action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
编辑:
基于这个线程:
不能使用Firebase Console设置click_action有效负载。您可以尝试使用curl命令或自定义http服务器进行测试
curl --header "Authorization: key=<YOUR_KEY_GOES_HERE>"
--header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send
-d "{\"to\":\"/topics/news\",\"notification\":
{\"title\": \"Click Action Message\",\"text\": \"Sample message\",
\"click_action\":\"OPEN_ACTIVITY_1\"}}"