13

我正在检查Firebase Cloud Messaging以发送通知。已经实现它并在应用程序处于打开状态时接收通知。但如果我关闭应用程序,它不再发出通知。有什么解决方案。

代码:

WebRequest wRequest;
wRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
wRequest.Method = "post";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));

wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

string postData = "{\"registration_ids\":[\"" + regIds + "\"], \"data\": "+ value +"}";

Byte[] bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;

Stream stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();

WebResponse wResponse = wRequest.GetResponse();

消息服务-

public class MessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Map<String, String>  data = remoteMessage.getData();
        sendNotification(data);
    }

    public void showMessage(Map<String, String>  serverData) {
        Intent i = new Intent(this,MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle(serverData.get("Title"))
                .setContentText(serverData.get("Message"))
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentIntent(pendingIntent);

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

        manager.notify(Integer.parseInt(serverData.get("ItemId")),builder.build());
    }

    private void sendNotification(Map<String, String>  serverData) {
        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_UPDATE_CURRENT);

        long[] pattern = {500,500,500,500,500};

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentTitle(serverData.get("Title"))
                .setContentText(serverData.get("Message"))
                .setAutoCancel(true)
                .setVibrate(pattern)
                .setLights(Color.BLUE,1,1)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(Integer.parseInt(serverData.get("ItemId")), notificationBuilder.build());
    }

}

主要活动-

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       FirebaseMessaging.getInstance().subscribeToTopic("test");
        FirebaseInstanceId.getInstance().getToken();
    }
}

显现-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="test.com.firebasenotify">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".InstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

    </application>

</manifest>
4

5 回答 5

10

代码没有问题。我正在使用 Mi note 4,但不知何故,当应用程序关闭时,它不会在 Mi4 中显示通知。我用其他安卓设备测试过,它工作正常。

感谢 Tim Castelijns 和 Frank van Puffelen 参与对话。

于 2016-06-20T10:11:52.790 回答
2

这里有关于这个问题的很好的解决方案和解释。您需要为通知设置高优先级以告诉android立即做出反应,否则需要几分钟才能显示收到的通知。

于 2020-11-03T14:40:04.937 回答
0

我使用旧版服务器密钥而不是它对我有用的服务器密钥。

于 2019-06-20T05:14:48.613 回答
-1

在您的 POST Payload 中添加time_to_live键将解决此问题。此参数的值必须是从 0 到 2,419,200 秒的持续时间,它对应于 FCM 存储和尝试传递消息的最长时间。“time_to_live”:3 参考 Firebase 文档

于 2016-08-23T04:45:05.033 回答
-3

根据FCM文档onMessageReceived()将不会在应用程序处于后台时被调用。您应该按顺序发送通知对象以将其显示在系统托盘中,并且当用户单击它时,启动器活动将打开,其中包含带有意图的附加数据。对于有效负载,您应该使用数据对象。在 Android 应用中查看文档和接收消息

于 2016-10-24T07:41:06.093 回答