如何在用户退出应用程序时显示消息通知?

时间:2017-06-29 23:25:56

标签: android firebase firebase-realtime-database notifications

我在那里使用firebase我可以看到添加新的“Child”时,我需要在添加新子时显示通知 我正在使用此代码,但它不起作用

(通知工作但只是在活动中显示,我需要在用户离开应用时显示通知,例如facebook或whatsapp

方法:

public Notification createNotification(boolean makeHeadsUpNotification) {
    Notification.Builder notificationBuilder = new Notification.Builder(this)
            .setSmallIcon(R.drawable.ic_settings_real_black_24dp)
            .setPriority(Notification.PRIORITY_DEFAULT)
            .setContentTitle("Sample Notification")
            .setContentText("This is a normal notification.");


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            notificationBuilder.setCategory(Notification.CATEGORY_MESSAGE);
        }

    if (makeHeadsUpNotification) {
        Intent push = new Intent();
        push.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        push.setClass(this, UserActivity.class);

        PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
                push, PendingIntent.FLAG_CANCEL_CURRENT);
        notificationBuilder
                .setContentText("Heads-Up Notification on Android L or above.")
                .setFullScreenIntent(fullScreenPendingIntent, true);
    }
    return notificationBuilder.build();
}

//添加子项时的通知方法

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


   // THIS METHODS ARE IN THE ONCREATE

    mListener = FirebaseUtils.getCHATSOLICITUDRef("8HaKY67AjaOD2a6QKrABhR2rcaJ3").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {


             /// THE METHOD IS IN THIS
            mNotificationManager.notify(1, createNotification(
                    true));
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });




}

1 个答案:

答案 0 :(得分:1)

您可以使用Services,因此它可以在后台运行,也可以查看我的代码here