我的代码没有错误,但是通知不会出现在我的Android手机中(我尝试过Android 8.0&9.0)。我希望通知一经检测到Firebase的值低于50,便立即显示。我什至尝试单击按钮以调用通知,但仍无法正常工作。
请帮帮我,谢谢
这是我的代码
public class IService extends Service {
private final String CHANNEL_ID="personal_notifications";
private final int NOTIFICATION_ID=001;
public IService() {
}
NotificationManagerCompat notificationManager;
DatabaseReference database=FirebaseDatabase.getInstance().getReference();
public void onCreate(){
super.onCreate();
notificationManager=NotificationManagerCompat.from(this);
database.child("Moisture").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot noteDataSnapshot: dataSnapshot.getChildren()){
Integer value=noteDataSnapshot.getValue(Integer.class);
if(value<50){
displayNotification();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void displayNotification(){
createNotificationChannel();
Intent landingIntent= new Intent(this,MainGarden.class);
landingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent landingPendingIntent= PendingIntent.getActivity(this,0,landingIntent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder= new NotificationCompat.Builder(this,CHANNEL_ID);
builder.setSmallIcon(R.drawable.alarm);
builder.setContentTitle("Alert! ");
builder.setContentText(" There is a strong vibration detected on the Front Door");
builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
builder.setContentIntent(landingPendingIntent);
builder.setAutoCancel(true);
NotificationManagerCompat notificationManagerCompat= NotificationManagerCompat.from(this);
notificationManagerCompat.notify(NOTIFICATION_ID,builder.build());
}
private void createNotificationChannel()
{
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
CharSequence name= "Personal Notifications";
String description = "Include all the personal notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,name,importance);
notificationChannel.setDescription(description);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
答案 0 :(得分:0)
点击此链接以获取正确答案。您是否添加了在Firebase控制台中创建的google.json文件。如果没有,那么首先创建json并将其添加到您的项目中。
在Android for Push通知中,您可以使用Firebase通知。这是在Android应用中添加通知功能的简便方法。
打开此链接,然后按照以下步骤实施推送通知。