如何在我的应用中显示通知?因为如果我发送消息无法在其他人中显示通知。体现在这里
<service
android:name=".FirebaseService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_SERVICE" />
</intent-filter>
</service>
<service
android:name=".FirebaseMessaging"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
类 apiservice
public interface APIService {
@Headers({
"Content-Type:application/json",
"Authorization:key=WKFqL"
})
@POST("fcm/send")
Call<Respon> sendnotif(@Body Pengirim body); }
课堂反应
public class Respon {
public int sukses;
}
类firebase消息传递
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());
} }
类firebase服务
public class FirebaseService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String tokenrf = FirebaseInstanceId.getInstance().getToken();
if(user != null){
updatetoken(tokenrf);
}
}
private void updatetoken(String tokenrf) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Tokens");
Tokenclass token = new Tokenclass(tokenrf);
ref.child(user.getUid()).setValue(token);
} }
sendnotif 的课堂聊天
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReferenceuser;
ValueEventListener seenlist;
DatabaseReference databaseReferenceseen;
List<Datachat> chatlist;
Adapterchat adapterchat;
APIService apiService;
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);
firebaseAuth = FirebaseAuth.getInstance();
Intent chatt = getIntent();
hisUid = chatt.getStringExtra("hisUid");
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
apiService = getRetrofit("https://fcm.googleapis.com/").create(APIService.class);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReferenceuser = firebaseDatabase.getReference("Users");
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("");
}
});
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);
String msg = pesan;
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());
apiService.sendnotif(pengirim)
.enqueue(new Callback<Respon>() {
@Override
public void onResponse(Call<Respon> call, retrofit2.Response<Respon> response) {
Toast.makeText(ChatAct.this, ""+response.message(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
如何在我的应用中显示通知?因为如果我发送消息无法在其他人中显示通知。