Уведомление не отображается, но код работает нормально - PullRequest
0 голосов
/ 20 ноября 2018

в моем коде нет ошибок, но уведомление не появится в моем телефоне 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");
    }
}

1 Ответ

0 голосов
/ 20 ноября 2018

Перейдите по этой ссылке для правильного ответа. Вы добавили файл google.json, созданный в консоли Firebase. Если нет, то сначала создайте и добавьте json в свой проект.

В Android для Push-уведомлений вы можете использовать Firebase-уведомления. Это простой способ добавить функциональность уведомлений в приложение для Android.

https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

Откройте эту ссылку и выполните следующие действия для реализации push-уведомлений.

...