【问题标题】:Android notification opens multiple times instead of only onceAndroid 通知打开多次而不是只打开一次
【发布时间】:2019-01-13 18:18:21
【问题描述】:

我正在尝试在将孩子添加到我的 Firebase 实时数据库时显示通知。只有当添加的孩子与当前用户密钥匹配时,该通知才必须打开。

添加孩子时它会正常显示,但每次我打开应用程序(On Create 方法)时它都会一次又一次地显示。在某种程度上,这确实很好。 而且,它会在每次应用程序被终止或添加另一个孩子时显示,即使用户键不是当前用户也是如此。

此外,有时,当通知打开时,它会同时重复 2 或 3 次。

这是服务的代码

public class ListenTheOrderAgain extends Service {

    //Firebase
    FirebaseDatabase db;
    DatabaseReference orders;
    Query query;

    FirebaseAuth auth;
    FirebaseUser user;
    String currenNego;
    DatabaseReference socioReff;

    private String negocioOn, off;

    @Override
    public void onCreate() {
        super.onCreate();

        auth = FirebaseAuth.getInstance();
        user = auth.getCurrentUser();

        if(user == null){


        } else {

            currenNego = auth.getCurrentUser().getUid();
            socioReff = FirebaseDatabase.getInstance().getReference().child("Shippers").child(currenNego);

        }


        db = FirebaseDatabase.getInstance();
        orders = db.getReference("Solicitudes");

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if(user == null){


        } else {

            socioReff.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    if((dataSnapshot.exists()) && (dataSnapshot.hasChild("is_working"))){

                        query = orders.orderByChild("shipper").equalTo(currenNego);

                        query.addChildEventListener(new ChildEventListener() {
                            @Override
                            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                                //Trigger here

                                PedidoModel result = dataSnapshot.getValue(PedidoModel.class);

                                if (result.getShipper().equals(currenNego)) {

                                    showNotification8(dataSnapshot.getKey(), result);
                                }

                            }

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

                            }

                            @Override
                            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

                            }

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

                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }
                        });

                        ///end

                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

        }
        return super.onStartCommand(intent, flags, startId);
    }



    public ListenTheOrderAgain() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }



    public void showNotification8(String key, PedidoModel request) {
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent , 0);

        int notificationId = 1;
        String channelId = "channel-01";
        String channelName = "Channel Name";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(
                    channelId, channelName, importance);
            notificationManager.createNotificationChannel(mChannel);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), channelId)
                    .setTicker("Test Order")
                    .setContentInfo("New Order")
                    .setContentText("Hello, you have a new Order #" + key)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(contentIntent);


            TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
            stackBuilder.addNextIntent(intent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );
            mBuilder.setContentIntent(resultPendingIntent);

            notificationManager.notify(notificationId, mBuilder.build());



        } else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){


            Intent intents = new Intent(getApplicationContext(), MainActivity.class);
            PendingIntent contentIntents = PendingIntent.getActivity(getApplicationContext(), 0, intent , 0);

            NotificationCompat.Builder builders = new NotificationCompat.Builder(getApplicationContext());

            builders.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                    .setTicker("Test Order")
                    .setContentInfo("New Order")
                    .setContentText("Hello you have a new ORder #" + key)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(contentIntents)
                    .setLights(Color.BLUE, 500, 500);



            NotificationManager managers = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

            //IF YOU WANT TO MANY NOTFICATION SHOW, YOU NEED GIVE UNIQUE ID OFR ECHA NOTIFICAICION

            int randomInt = new Random().nextInt(9999-1)+1;
            managers.notify(randomInt, builders.build());

        }
    }
}

这就是我从主要活动中调用服务的方式:

    //Call service
    Intent service = new Intent(MainActivity.this, ListenTheOrderAgain.class);
    startService(service);

请帮帮我!

【问题讨论】:

    标签: java android firebase firebase-realtime-database


    【解决方案1】:

    我认为最好创建一个 FirebaseMessagingService:

    在清单中:

    <service
            android:name=".ListenTheOrderAgain"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
    

    在您的服务中:

    public class ListenTheOrderAgain extends FirebaseMessagingService {
    
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    
    //your code for reading notifications
    }
    

    而且您不必调用 startService。没有它,这项服务也能正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      相关资源
      最近更新 更多