我想通过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]", ""));
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);
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 i, int i1, 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_qn1o4J3BjggWnL5SnOsEDTPCaNuZXdHI4ZI70GMzo7HB_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));
}
}