从Firebase接收通知时触发警报

时间:2017-08-24 16:38:31

标签: android firebase push-notification firebase-cloud-messaging

在我的应用程序中,我将有一个外部服务,它将向firebase发送消息,firebase将向特定主题中的所有设备发送通知。到目前为止,我可以收到通知,但是当它发生时我需要发出警报。

问题是:我收到通知但无法启动闹钟。

到目前为止,这是我的接收器代码:

    public class MessageReceiver extends FirebaseMessagingService {
    private static final String TAG = "FCM Service";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO: 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.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 0, pintent);
        alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pintent);

    }
}

并表明:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="XXXXXXXXXXXX">
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <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">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <service
            android:name=".MessageReceiver">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                <action android:name="android.intent.action.RESPOND_VIA_MESSAGE"/>
            </intent-filter>
        </service>
        <service android:name=".FirebaseIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

您没有说明问题所在。我假设MainActivity没有开始。这很可能是由于这句话引起的:

PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);

因为你想要启动一个Activity而不是一个Service,它应该是:

PendingIntent pintent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);