在我的应用中,我将有一个外部服务,该服务将向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);