我将让我的通知适用于许多活动,我既不知道该如何做,也不知道该如何开始,但我已经能够找到如何获取消息通知的方法。是否可以使用它来通知其他人?如果是这样,请帮助我
package com.developer.fireone.finga.Notifications;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import androidx.core.app.NotificationCompat;
import com.developer.fireone.finga.MessageActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.prefs.Preferences;
/**
* Created by user on 13/02/2019.
*/
public class MyFirebaseMessaging extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String sented = remoteMessage.getData().get("sented");
String user = remoteMessage.getData().get("user");
SharedPreferences preferences = getSharedPreferences("PREFS", MODE_PRIVATE);
String currentUser= preferences.getString("currentuser","none");
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if(firebaseUser!=null && sented.equals(firebaseUser.getUid())){
if(!currentUser.equals(user)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
sendOreoNotification(remoteMessage);
} else {
sendNotification(remoteMessage);
}
}
}
}
private void sendOreoNotification(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 j = Integer.parseInt(user.replaceAll("[\\D]", ""));
Intent intent = new Intent(this, MessageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("userid", user);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,j,intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
OreoNotification oreoNotification = new OreoNotification(this);
Notification.Builder builder = oreoNotification.getOreoNotification(title, body, pendingIntent,
defaultSound, icon);
int i = 0;
if(j>0){
i=j;
}
oreoNotification.getManager().notify(i, builder.build());
}
private void sendNotification(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 j = Integer.parseInt(user.replaceAll("[\\D]", ""));
Intent intent = new Intent(this, MessageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("userid", user);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,j,intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(Integer.parseInt(icon))
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentIntent(pendingIntent);
NotificationManager noti = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int i = 0;
if(j>0){
i=j;
}
noti.notify(i, builder.build());
}
}
CommentActivity(请给我一个带有Commentactivity的命令)
package com.developer.fireone.finga;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.developer.fireone.finga.Adapter.CommentAdapter;
import com.developer.fireone.finga.Fragment.APIService;
import com.developer.fireone.finga.Model.Comment;
import com.developer.fireone.finga.Model.User;
import com.developer.fireone.finga.Notifications.Client;
import com.developer.fireone.finga.Notifications.Data;
import com.developer.fireone.finga.Notifications.MyResponse;
import com.developer.fireone.finga.Notifications.Sender;
import com.developer.fireone.finga.Notifications.Token;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CommentsActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private CommentAdapter commentAdapter;
private List<Comment> commentList;
EditText addcomment;
ImageView image_profile;
TextView post;
String postid;
String publisherid, currentDate, currentTime;
FirebaseUser firebaseUser;
Intent intent;
APIService apiService;
boolean notify = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.comments1);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
//apiservice
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIService.class);
Intent intent = getIntent();
postid = intent.getStringExtra("postid");
publisherid = intent.getStringExtra("publisherid");
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
commentList = new ArrayList<>();
commentAdapter = new CommentAdapter(this, commentList, postid);
recyclerView.setAdapter(commentAdapter);
addcomment = findViewById(R.id.add_comment);
image_profile = findViewById(R.id.image_profile);
post = findViewById(R.id.post);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
post.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
notify=true;
if(addcomment.getText().toString().equals("")){
Toast.makeText(CommentsActivity.this, R.string.pasdecommentvide, Toast.LENGTH_SHORT).show();
}else{
addComment();
}
}
});
getImage();
readComments();
}
private void addComment() {
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDateFormat = new SimpleDateFormat("MMM dd, yyyy");
currentDate = currentDateFormat.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTimeFormat = new SimpleDateFormat("hh:mm a");
currentTime = currentTimeFormat.format(calForTime.getTime());
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments").child(postid);
String commentid = reference.push().getKey();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("comment", addcomment.getText().toString());
hashMap.put("publisher", firebaseUser.getUid());
hashMap.put("commentid", commentid);
hashMap.put("date", currentDate);
hashMap.put("time", currentTime);
reference.child(commentid).setValue(hashMap);
addNotifications();
addcomment.setText("");
reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user =dataSnapshot.getValue(User.class);
if(notify) {
sendNotificaion(firebaseUser.getUid(), user.getUsername(), addcomment.getText().toString());//here is what i try to follow it does not work
}
notify=false;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//here is what i try to follow it does not work
private void sendNotificaion(String receiver, final String username, final String msg) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query query = tokens.orderByKey().equalTo(receiver);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
Token token = snapshot.getValue(Token.class);
Data data = new Data(firebaseUser.getUid(), R.mipmap.logo4, username+": "+msg, "New Comment", postid );
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(CommentsActivity.this, R.string.failed, Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void addNotifications(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(publisherid);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("userid", firebaseUser.getUid());
hashMap.put("text", getString(R.string.commenterxa)+" "+addcomment.getText().toString());
hashMap.put("postid", postid);
hashMap.put("ispost", true);
hashMap.put("isseen", false);
reference.push().setValue(hashMap);
}
private void getImage(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.keepSynced(true);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final User user = dataSnapshot.getValue(User.class);
Glide.with(getApplicationContext()).load(user.getImageurl()).into(image_profile);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void readComments(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments").child(postid);
reference.keepSynced(true);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
commentList.clear();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
Comment comment = snapshot.getValue(Comment.class);
commentList.add(comment);
}
commentAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
评论
package com.developer.fireone.finga.Model;
/**
* Created by user on 13/12/2018.
*/
public class Comment {
private String comment;
private String publisher;
private String commentid;
private String date;
private String time;
public Comment() {
}
public Comment(String comment, String publisher, String commentid, String date, String time) {
this.comment = comment;
this.publisher = publisher;
this.commentid = commentid;
this.date = date;
this.time = time;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getCommentid() {
return commentid;
}
public void setCommentid(String commentid) {
this.commentid = commentid;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}