无法使用Firebase推送聊天通知

问题描述

我想通过Firebase发送推送通知,但不起作用,我的logcat中收到以下错误消息

D/JSON_RESPONSE: onResponse: {"multicast_id":9122914136814393874,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1598183030158480%51951e0af9fd7ecd"}]}

此应用可以发送聊天,用户可以接收聊天,但是在收到聊天时不会显示通知

这是我的代码

    public class FirebaseMessaging extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        SharedPreferences shr = getSharedPreferences("SP_USER",MODE_PRIVATE);
        String savedc = shr.getString("Current_USERID","None");//

        String sent = remoteMessage.getData().get("sent");
        String user = remoteMessage.getData().get("user");
        FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        if(firebaseUser != null && sent != null && sent.equals(firebaseUser.getUid())) {
            if (!savedc.equals(user)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    sendnotif(remoteMessage);
                } else {
                    sendnormal(remoteMessage);
                }
            }
        }
    }


    private void sendnormal(RemoteMessage remoteMessage) {

        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification = remoteMessage.getNotification();
        int a = Integer.parseInt(user.replaceAll("[\\D]",""));
        Intent intent = new Intent(this,ChatAct.class);
        Bundle bundle = new Bundle();
        bundle.putString("hisUid",user);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,a,intent,PendingIntent.FLAG_ONE_SHOT);
        Uri soundur = ringtoneManager.getDefaultUri(ringtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(Integer.parseInt(icon))
                .setContentText(body)
                .setContentTitle(title)
                .setAutoCancel(true)
                .setSound(soundur)
                .setContentIntent(pendingIntent);
        notificationmanager notificationmanager = (notificationmanager)getSystemService(Context.NOTIFICATION_SERVICE);
        int j = 0;
        if (a>0){
            j=a;

        }
        notificationmanager.notify(j,builder.build());

    }


    private void sendnotif(RemoteMessage remoteMessage) {
        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification = remoteMessage.getNotification();
        int a = Integer.parseInt(user.replaceAll("[\\D]",PendingIntent.FLAG_ONE_SHOT);
        Uri soundur = ringtoneManager.getDefaultUri(ringtoneManager.TYPE_NOTIFICATION);

        Notif notif = new Notif(this);
        Notification.Builder builder = notif.getnotif(title,body,pendingIntent,soundur,icon);


         int j = 0;
        if (a>0){
            j=a;

        }
        notif.getnotificationmanager().notify(j,builder.build());
    }

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if(user!=null){

            updatetoken(s);
        }
    }

    private void updatetoken(String s) {

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Tokens");
        Tokenclass token = new Tokenclass(s);
        ref.child(user.getUid()).setValue(token);


    }
}

这是ChatActivity类的代码

  public class ChatAct extends AppCompatActivity {

    Toolbar toolbar;
    RecyclerView recyclerView;
    CircleImageView imgprof;
    TextView namacht,statuson;
    EditText pesanet;
    ImageButton sendbtn;
    FirebaseAuth firebaseAuth;
    String hisUid;
    String myUid,hisImage;

    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReferenceuser;

    ValueEventListener seenlist;
    DatabaseReference databaseReferenceseen;
    FirebaseUser fuser;

    List<Datachat> chatlist;
    Adapterchat adapterchat;

    private RequestQueue requestQueue;
    private boolean notify = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        toolbar = findViewById(R.id.toolbr);
        setSupportActionBar(toolbar);
        toolbar.setTitle("");
        recyclerView = findViewById(R.id.cht_recycler);
        imgprof = findViewById(R.id.profimg);
        namacht = findViewById(R.id.namacht);
        statuson = findViewById(R.id.statuson);
        pesanet = findViewById(R.id.pesanet);
        sendbtn = findViewById(R.id.sendbtn);

        requestQueue = Volley.newRequestQueue(getApplicationContext());

        firebaseAuth = FirebaseAuth.getInstance();
        fuser = FirebaseAuth.getInstance().getCurrentUser();

        Intent chatt = getIntent();
        hisUid = chatt.getStringExtra("hisUid");

        linearlayoutmanager linearlayoutmanager = new linearlayoutmanager(this);
        linearlayoutmanager.setStackFromEnd(true);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(linearlayoutmanager);


        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReferenceuser = firebaseDatabase.getReference("Users");

        Query queryu = databaseReferenceuser.orderByChild("uid").equalTo(hisUid);
        queryu.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot ds: dataSnapshot.getChildren()){

                    String name = ""+ds.child("name").getValue();
                    hisImage = ""+ds.child("image").getValue();
                    String onstatus = ""+ ds.child("onlinesT").getValue();
                    String ketikan = ""+ ds.child("mengetik").getValue();

                    if(ketikan.equals(myUid)){
                        statuson.setText("Sedang Mengetik...");
                    }
                    else{
                        if(onstatus.equals("online")){
                            statuson.setText(onstatus);
                        }

                        else{
                            statuson.setText("");

                        }
                    }



                    namacht.setText(name);
                    try{
                        Picasso.get().load(hisImage).placeholder(R.drawable.ic_usr_name).into(imgprof);
                    }
                    catch (Exception e){


                    }
                }
            }

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

            }
        });

        sendbtn.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                notify = true;

                String pesan = pesanet.getText().toString().trim();
                if(TextUtils.isEmpty(pesan)){

                    Toast.makeText(ChatAct.this,"Tidak dapat mengirim pesan kosong",Toast.LENGTH_SHORT).show();

                }
                else{
                    kirimpesan(pesan);
                }
                pesanet.setText("");
            }
        });

        bacapesan();

        dilihat();

        pesanet.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence,int i,int i1,int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence,int i2) {

                if(charSequence.toString().trim().length() ==0){
                    cekketik("tidakada");
                }
                else{
                    cekketik(hisUid);
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void dilihat() {
        databaseReferenceseen = FirebaseDatabase.getInstance().getReference("Chats");
        seenlist = databaseReferenceseen.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot ds: dataSnapshot.getChildren()){
                    Datachat chat = ds.getValue(Datachat.class);
                    if(chat.getReceiver().equals(myUid) && chat.getSender().equals(hisUid)){
                        HashMap<String,Object> hasSeenHashMap = new HashMap<>();
                        hasSeenHashMap.put("seen",true);
                        ds.getRef().updateChildren(hasSeenHashMap);
                    }
                }

            }

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

            }
        });
    }

    private void bacapesan() {
        chatlist = new ArrayList<>();
        DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Chats");
        dbref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                chatlist.clear();
                for(DataSnapshot ds: dataSnapshot.getChildren()){
                    Datachat chat = ds.getValue(Datachat.class);
                    if(chat.getReceiver().equals(myUid) && chat.getSender().equals(hisUid) ||
                    chat.getReceiver().equals(hisUid) && chat.getSender().equals(myUid)){
                        chatlist.add(chat);
                    }

                    adapterchat = new Adapterchat(ChatAct.this,chatlist,hisImage);
                    adapterchat.notifyDataSetChanged();
                    recyclerView.setAdapter(adapterchat);
                }

            }

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

            }
        });
    }

    private void kirimpesan(final String pesan) {
        DatabaseReference databaseReference =FirebaseDatabase.getInstance().getReference();

        String timestamp = String.valueOf(System.currentTimeMillis());

        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("sender",myUid);
        hashMap.put("receiver",hisUid);
        hashMap.put("message",pesan);
        hashMap.put("seen",false);
        hashMap.put("timestamp",timestamp);
        databaseReference.child("Chats").push().setValue(hashMap);



        final DatabaseReference database = FirebaseDatabase.getInstance().getReference("Users").child(myUid);
        database.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                DataUser user = dataSnapshot.getValue(DataUser.class);
                if(notify){
                    sendnotif(hisUid,user.getName(),pesan);
                }
                notify = false;

            }

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

            }
        });

    }

    private void sendnotif(final String hisUid,final String name,final String pesan) {

        DatabaseReference alltoken = FirebaseDatabase.getInstance().getReference("Tokens");
        Query query = alltoken.orderByKey().equalTo(hisUid);
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot ds: dataSnapshot.getChildren()){
                    Tokenclass tokenclass = ds.getValue(Tokenclass.class);
                    Datanotif data = new Datanotif(myUid,name + ":" + pesan,"Pesan Baru",hisUid,R.drawable.ic_usr_name);
                    Pengirim pengirim = new Pengirim(data,tokenclass.getToken());

                    try{

                        JSONObject senderobj = new JSONObject(new Gson().toJson(pengirim));
                        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send",senderobj,new Response.Listener<JSONObject>() {
                                    @Override
                                    public void onResponse(JSONObject response) {

                                        Log.d("JSON_RESPONSE","onResponse: "+ response.toString());
                                    }
                                },new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.d("JSON_RESPONSE","onResponse: "+ error.toString());

                            }
                        }){
                            @Override
                            public Map<String,String> getHeaders() throws AuthFailureError {

                                Map<String,String> headers = new HashMap<>();
                                headers.put("Content-Type","application/json");
                                headers.put("Authorization","key=AAAaimjs9vw:APA91bFnhPsORo2XbYqFyRbisa6SMOakNMjpnR6GFfeeaAxA_qn1o4J3BjggWnL5SnOsEDTPCaNuZXdHI4编程之家0GMzo7HB_pHxvEkr0iWX4w_QefCpIz2O1J71X5oyhxEw5Ak8YSRTNFx");
                                return headers;
                            }
                        };

                        requestQueue.add(jsonObjectRequest);

                    } catch (JSONException e){
                        e.printstacktrace();
                    }

                }
            }

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

            }
        });

    }

    private void setSupportActionBar(Toolbar toolbar) {

    }

    private void checkuser(){

        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null){

            myUid = user.getUid();

        }

        else{
            startActivity(new Intent(this,MainActivity.class));
           finish();
        }
    }



    private void  checkOnline(String status){
        DatabaseReference dbrf = FirebaseDatabase.getInstance().getReference("Users").child(myUid);
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("onlinesT",status);

        dbrf.updateChildren(hashMap);
    }

    private void  cekketik(String mengetik){
        DatabaseReference dbrf = FirebaseDatabase.getInstance().getReference("Users").child(myUid);
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("mengetik",mengetik);

        dbrf.updateChildren(hashMap);
    }

    @Override
    protected void onStart() {
        checkuser();
        checkOnline("online");
        super.onStart();
    }

    @Override
    protected void onPause() {

        super.onPause();
        checkOnline("");
        cekketik("tidakada");
        databaseReferenceseen.removeEventListener(seenlist);

    }

    @Override
    protected void onResume() {
        checkOnline("online");
        super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.logout,menu);
        menu.findItem(R.id.searchin).setVisible(false);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public  boolean onoptionsItemSelected(MenuItem item){
        int id = item.getItemId();
        if(id==R.id.logout){
            firebaseAuth.signOut();
            checkuser();
        }
        return super.onoptionsItemSelected(item);
    }
}

这是OreoNotif类的代码

public class Notif extends Contextwrapper {

private static final String ID = "some_id";
private static final String NAME = "uSocial";
private notificationmanager notificationmanager;

public Notif(Context base) {
    super(base);
    if(Build.VERSION.SDK_INT>Build.VERSION_CODES.O){
        createChannel();
    }
}

@TargetApi(Build.VERSION_CODES.O)
private void createChannel() {
    NotificationChannel notificationChannel = new NotificationChannel(ID,NAME,notificationmanager.IMPORTANCE_DEFAULT);
    notificationChannel.enableLights(true);
    notificationChannel.enableVibration(true);
    notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    getnotificationmanager().createNotificationChannel(notificationChannel);
}

public notificationmanager getnotificationmanager(){
    if(notificationmanager == null){
        notificationmanager = (notificationmanager)getSystemService(Context.NOTIFICATION_SERVICE);
    }
    return notificationmanager;
}

@TargetApi(Build.VERSION_CODES.O)
public Notification.Builder getnotif (String title,String body,PendingIntent pendingIntent,Uri sounduri,String icon){
    return new Notification.Builder(getApplicationContext(),ID)
            .setContentIntent(pendingIntent)
            .setContentTitle(title)
            .setContentText(body)
            .setSound(sounduri)
            .setAutoCancel(true)
            .setSmallIcon(Integer.parseInt(icon));
}


}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...