我正在学习如何从我的Firebase控制台发送定期通知到我的android应用程序:
Homepage.java:
protected void onCreate(@Nullable Bundle savedInstanceState) {
startService(new Intent(getApplicationContext(),firebase_connection.class));
//Here I am calling the service class
}
firebase_connection.java:
public class firebase_connection extends FirebaseMessagingService {
@Override
public void onMessageReceived(@NonNull RemoteMessage message) {
super.onMessageReceived(message);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("MyNotifications","MyNotifications", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
FirebaseMessaging.getInstance().subscribeToTopic("electric").addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
String msg = "Welcome to my app";
if(!task.isSuccessful())
msg = "Sorry";
Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
}
});
}
}
我的Firebase控制台:
这是我的日程通知
我一直等到上午9:40(如上面的截图中给出的通知设置),没有通知显示。我是新的Firebase,我在哪里出错了?请帮帮我。
我在实际设备上运行应用程序
你错过了很多东西。首先,您必须在AndroidManifest
中像这样在application
标签中声明FirebaseMessagingService
:
<service android:name=".firebase_connection">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
而不是在onCreate
方法中调用startService
,你必须订阅topic。现在,你正在订阅通知服务本身,这是完全错误的。
protected void onCreate(@Nullable Bundle savedInstanceState) {
FirebaseMessaging.getInstance().subscribeToTopic("electric").addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
String msg = "Welcome to my app";
if(!task.isSuccessful())
msg = "Sorry";
Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
}
});
}
最后,在FirebaseMessagingService
中,您只是创建一个通知通道,但不创建通知本身。这样做:
public class firebase_connection extends FirebaseMessagingService {
@Override
public void onMessageReceived(@NonNull RemoteMessage message) {
super.onMessageReceived(message);
NotificationManager manager = getSystemService(NotificationManager.class);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("channel1","My Notification", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("description");
manager.createNotificationChannel(channel);
}
if (remoteMessage.getNotification() != null) {
Notification notification = NotificationCompat.Builder(context, "channel1")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(message.getNotification().getTitle())
.setContentText(message.getNotification().getBody())
.build();
manager.notify(1, notification)
}
}
}
您可以像上面那样使用RemoteMessage
对象从Firebase控制台获取标题和文本。希望一切顺利!