How to show notification when user app run in background?

I was creating a chating application with using of firebase in android studio ,my all activity working properly expect my background notification , what I wanted is,user gets notifications when other user send the message and when user unseen the message and app runs in background.
I will try this but I got notification both the times when user chatting(seen message) and when user app run in background (unseenmessage)

here is my code

       apiService= Client.getClient("https://fcm.googleapis.com/").create(APIService.class);
         userref =to.getStringExtra("id");
                firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
                sendmsg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String textmsg=inputmsg.getText().toString();
                        if(!textmsg.equals("")){
        
                            String rand=randomString(10);
                            sendmessage(firebaseUser.getUid(),userref,textmsg,currentDate,currenttime,rand);
        
                            getnotifiactions(rand);
                        }
                        else{
                            Toast.makeText(chatscreen.this, "ENTER SOMETHING TO SEND ", Toast.LENGTH_SHORT).show();
                        }
                        inputmsg.setText("");
                    }
                });
     private  void sendmessage(String sender,String receiver,String message,String currentd_d ,String currenttime,String no){
            DatabaseReference reference1=  FirebaseDatabase.getInstance().getReference();
            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("sender",sender);
            hashMap.put("receiver",receiver);
            hashMap.put("message",message);
            hashMap.put("date",currentd_d);
            hashMap.put("time",currenttime);
            hashMap.put("isseen",false);
            hashMap.put("msgid",no);
            reference1.child("Chats").push().setValue(hashMap);
        }
 private  void seenmessage(String userid)
    {
        reference= FirebaseDatabase.getInstance().getReference("Chats");
        seenlisterner=reference.addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(@NonNull @NotNull DataSnapshot snapshot)
            {
                    for(DataSnapshot dataSnapshot:snapshot.getChildren())
                    {
                        Chat cht=dataSnapshot.getValue(Chat.class);
                        if(cht.getReceiver().equals(firebaseUser.getUid()) && cht.getSender().equals(userid) )
                        {
                            HashMap<String,Object> hashMap=new HashMap<>();
                            hashMap.put("isseen",true);
                            dataSnapshot.getRef().updateChildren(hashMap);
                        }                    }             }
        @Override
        public void onCancelled(@NonNull @NotNull DatabaseError error)
        {
        }
        });    }

here is notifications methods and calls

     private void getnotifiactions(String msgid) {
    
            reference= FirebaseDatabase.getInstance().getReference();
            Query query = reference.child("Chats").orderByChild("msgid").equalTo(msgid);
            query.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
                    for(DataSnapshot ds:snapshot.getChildren()) {
                        Chat ct=ds.getValue(Chat.class);
    
                        if(ct.getIsseen().equals(true)){
                            Toast.makeText(chatscreen.this, "Online", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                            Toast.makeText(chatscreen.this, "OFFLINE", Toast.LENGTH_SHORT).show();
                            sendnotification(ct.getReceiver(), ct.getMessage());}
                         }
                }
    
                @Override
                public void onCancelled(@NonNull @NotNull DatabaseError error) {
    
                }
            });
    
        }
private void sendnotification(String receiver, String msg) {
        DatabaseReference tokens=FirebaseDatabase.getInstance().getReference("Token");
        Query query=tokens.orderByKey().equalTo(receiver);
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
                for(DataSnapshot dataSnapshot:snapshot.getChildren()){

                    String fuserid=firebaseUser.getUid();
                    Token token=dataSnapshot.getValue(Token.class);

                    Data data=new Data(firebaseUser.getUid(),R.mipmap.ic_launcher," "+msg,"New MESSAGES",userref);
                    Sender sender=new Sender(data,token.getToken());
                    apiService.sendNotification(sender).enqueue(new Callback<Myresponse>() {
                                @Override
                                public void onResponse(Call<Myresponse> call, Response<Myresponse> response) {
                                    if(response.code()==200){
                                        if(response.body().success !=  1){
                                            Toast.makeText(chatscreen.this,"Failed", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }
                                @Override
                                public void onFailure(Call<Myresponse> call, Throwable t) {
                                }
                            });
                }
            }
            @Override
            public void onCancelled(@NonNull @NotNull DatabaseError error) {
            }
        });
    }

I only wants notifications when user app run in background, not when user chatting with other user.
anyone knows how to fix this ? please help me !

Source: Android Questions

LEAVE A COMMENT