在我的应用程序中,我将有一个外部服务,该服务会将消息发送到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>

最佳答案

您没有指出问题所在。我认为是MainActivity没有启动。这可能是由以下语句引起的:

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


因为您要启动一个活动而不是一个服务,所以它应该是:

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

关于android - 从Firebase接收通知时触发警报,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45866914/

10-10 23:20
查看更多