【问题标题】:Notifications not appearing in killed state of an application using firebase通知未出现在使用 firebase 的应用程序的终止状态
【发布时间】:2017-11-24 17:21:06
【问题描述】:

我正在尝试在上传帖子时向应用程序的最终用户推送通知。当应用程序处于前台和后台时它工作正常,但在应用程序被杀死或关闭时不显示(不在后台和前台)。有什么方法可以在应用程序关闭时显示通知。 这是我部署到 firebase 函数的 index.js 代码。

const functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPush = functions.database.ref('/promos').onWrite(event => {
var topic = "deals_notification";
let projectStateChanged = false;
let projectCreated = false;
let projectData = event.data.val();

if (((event.data.numChildren())-(event.data.previous.numChildren()))>0) {
    let msg="notification arrived"
  let payload = {
        data: {
             "msg":msg
        }
    };

admin.messaging().sendToTopic(topic, payload).then(function(response) {
console.log("Successfully sent message:", response);
}).catch(function(error) {
console.log("Error sending message:", error);
});
}
});

这里是 MyFirebaseMessageService:

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessageService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    sendnotification(remoteMessage.getData().get("msg"));
}
private void sendnotification(String body){
    Intent intent = new Intent(this, MainActivity.class);

  PendingIntent pIntent = PendingIntent.getActivity(this,0, intent, 0);
    Notification.Builder n  = new Notification.Builder(this)
            .setContentTitle("Best Deals")
            .setContentText(body)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pIntent)
            .setAutoCancel(true);

    NotificationManager manager = (NotificationManager) 
    getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(0, n.build());
}
}

编辑:这是清单文件。

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.priya.bestdeals">

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="25" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:name=".Application"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar"></activity>
    <activity android:name=".LoginActivity" />
    <activity android:name=".RegisterActivity" />
    <activity android:name=".Details">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="MainActivity" />
    </activity>
    <activity android:name=".Posts" />
    <activity android:name=".Settings" />
    <activity android:name=".Postdetails" />
    <activity android:name=".IntroActivity" />
    <activity
        android:name=".SplashScreen"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@android:style/Theme.Black.NoTitleBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".WriteActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="MainActivity" />
    </activity>
    <activity android:name=".DeleteActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="MainActivity" />
    </activity>
    <activity android:name=".EditProfile"></activity>
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_notifications_black_24dp" />

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorAccent" />
    <service
        android:name=".MyFirebaseInstanceIdService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    <service
        android:name=".MyFirebaseMessageService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

</application>

谢谢。

【问题讨论】:

  • 确保在清单中注册您的接收器
  • 感谢您的支持。我在编辑中添加了清单。我是使用 Firebase 通知的新手。您能否提及我应该对清单进行哪些更改,以便在关闭应用程序时收到通知。 @portfoliobuilder
  • 查看我的答案here(也包含在@BobSnyder 的答案中)。

标签: android node.js firebase push-notification firebase-cloud-messaging


【解决方案1】:

您需要在options object 中指定priority: "high" 才能调用sendToTopic()。如果设备处于空闲/打盹模式,这将唤醒设备以接收消息:

const options = {
  priority: "high"
};

admin.messaging().sendToTopic(topic, payload, options).then(...);

如果以高优先级发送消息没有帮助,那么您可能正在测试其中一款手机型号,当应用程序以某些方式被杀死时(例如从最近的任务中滑动)列表)。详情请见this answer

This answer包含华为/EMOI设备的解决方案。您可以将您的应用列入白名单以使其免于被强制停止:高级设置 > 电池 > 受保护的应用

【讨论】:

  • 我根据您的建议更新了代码。但是应用程序在关闭时仍然没有显示任何通知。我在 3 个不同的手机上尝试过,但结果仍然相同。您能否提出更多更改建议,以便应用即使在关闭时也能显示通知。
【解决方案2】:

其实你访问 RemoteMessage 的方式不对。

 @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }
}

private void handleDataMessage(JSONObject json) {
        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");
            String imageUrl = data.getString("image");
            String timestamp = data.getString("timestamp");
            JSONObject payload = data.getJSONObject("payload");

            Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);
            Log.e(TAG, "payload: " + payload.toString());
            Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);


            sendNotification(title,message);


            } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
}
private void sendNotification(String title,String message) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

更多细节见google官方例子

https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java#L45-L82

【讨论】:

    猜你喜欢
    • 2017-11-24
    • 1970-01-01
    • 2019-06-30
    • 2022-08-03
    • 2018-08-08
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多