Android应用在关闭时未收到FCM通知

时间:2016-06-16 10:38:41

标签: android notifications firebase firebase-cloud-messaging firebase-notifications

我正在检查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>

5 个答案:

答案 0 :(得分:8)

代码没有问题。我正在使用Mi note 4,并且当app关闭时,它不会在Mi4中显示通知。我测试了其他Android设备,并且工作正常。

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

答案 3 :(得分:-1)

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

答案 4 :(得分:-3)

根据 FCM ,当应用处于后台时,不会调用 onMessageReceived()。您应该发送通知对象以便在系统托盘中显示该对象,当用户点击它时,启动器活动将打开,数据为 extras 使用意图。对于有效负载,您应该使用数据对象。 see docsReceive Messages in an Android App