使用Android应用程序向FCM发送通知
我想构建客户端和管理员android应用程序,以便管理员应用程序向FCM(API)发送通知,并且客户端应用程序的用户获得此通知使用Android应用程序向FCM发送通知,android,firebase,firebase-cloud-messaging,Android,Firebase,Firebase Cloud Messaging,我想构建客户端和管理员android应用程序,以便管理员应用程序向FCM(API)发送通知,并且客户端应用程序的用户获得此通知 implementation 'com.google.firebase:firebase-messaging:20.1.3' implementation 'com.google.firebase:firebase-analytics:17.2.3' 因此,我使用Firebase Admin SDK通过使用将通知从Admin应用程序推送到FCM,但在下一段代码(来自文
implementation 'com.google.firebase:firebase-messaging:20.1.3'
implementation 'com.google.firebase:firebase-analytics:17.2.3'
因此,我使用Firebase Admin SDK通过使用将通知从Admin应用程序推送到FCM,但在下一段代码(来自文档)中有一些奇怪的地方
由于
send(RemoteMessage)
接受RemoteMessage
而不是Message
对象,因此我如何修改之前的代码以使用RemoteMessage
object发送通知您似乎试图将Firebase Admin SDK与用于Android的Firebase Cloud Messaging SDK混合使用。这是不可能的
任何使用Admin SDK的进程都被授予对Firebase项目的完全、无限制访问权限。因此,如果您将其放在客户端应用程序中,使用该应用程序的每个人都可以向您的任何用户发送FCM消息,但也可以:列出所有用户、删除整个数据库、覆盖云功能等。因此,Firebase Admin SDK应该/只能在受信任的环境中使用,例如您的开发机器,您控制的服务器或云功能
要通过Firebase云消息向设备发送消息,您始终需要一个受信任的环境,通常在FCM文档中称为应用程序服务器
当您在受信任的环境上运行Admin SDK时,可以调用,它将build()
返回的消息作为其参数
另见:
- 我的博客帖子
- 这是使用Node.js实现的
使用我的代码像符咒一样工作:
向特定用户发送通知并管理通知的单击
implementation 'com.google.firebase:firebase-messaging:20.1.3'
implementation 'com.google.firebase:firebase-analytics:17.2.3'
显示
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="default_channel_id" />
<service
android:name=".FCMService" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
发送通知时
new Thread(new Runnable() {
@Override
public void run() {
pushNotification(senderName + " : " + message);
}
}).start();
private void pushNotification(String message) {
JSONObject jPayload = new JSONObject();
JSONObject jNotification = new JSONObject();
JSONObject jData = new JSONObject();
try {
// notification can not put when app is in background
jNotification.put("title", getString(R.string.app_name));
jNotification.put("body", message);
jNotification.put("sound", "default");
jNotification.put("badge", "1");
jNotification.put("icon", "ic_notification");
// jData.put("picture", "https://miro.medium.com/max/1400/1*QyVPcBbT_jENl8TGblk52w.png");
//to token of any deivce
jPayload.put("to", device_token);
// data can put when app is in background
jData.put("goto_which", "chatactivity");
jData.put("user_id", mCurrentUserId);
jPayload.put("priority", "high");
jPayload.put("notification", jNotification);
jPayload.put("data", jData);
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "key=" + AUTH_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// Send FCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jPayload.toString().getBytes());
// Read FCM response.
InputStream inputStream = conn.getInputStream();
final String resp = convertStreamToString(inputStream);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
private String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next().replace(",", ",\n") : "";
}
添加服务类
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FCMService extends FirebaseMessagingService {
String goto_which, user_id;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("ff", "messddda recice: " + remoteMessage.getNotification().getTicker());
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
if (remoteMessage.getData().size() > 0) {
goto_which = remoteMessage.getData().get("goto_which").toString();
user_id = remoteMessage.getData().get("user_id").toString();
Log.d("ff", "messddda send: " + goto_which);
}
sendnotification(title, body, goto_which, user_id);
}
private void sendnotification(String title, String body, String goto_which, String user_id) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("goto_which", goto_which);
intent.putExtra("user_id", user_id);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultsounduri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder nbuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultsounduri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, nbuilder.build());
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w("f", "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
}
});
}
}
你在标题中提到SVM。这是我不熟悉的首字母缩略词。这是什么意思?您标记了android,但Firebase Admin SDK并不用于客户端应用程序代码(因为它授予运行过程对Firebase项目的无限访问权)。您试图在哪里运行此代码?
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FCMService extends FirebaseMessagingService {
String goto_which, user_id;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("ff", "messddda recice: " + remoteMessage.getNotification().getTicker());
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
if (remoteMessage.getData().size() > 0) {
goto_which = remoteMessage.getData().get("goto_which").toString();
user_id = remoteMessage.getData().get("user_id").toString();
Log.d("ff", "messddda send: " + goto_which);
}
sendnotification(title, body, goto_which, user_id);
}
private void sendnotification(String title, String body, String goto_which, String user_id) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("goto_which", goto_which);
intent.putExtra("user_id", user_id);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultsounduri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder nbuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultsounduri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, nbuilder.build());
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w("f", "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
}
});
}
}
if (getIntent().getExtras() != null) {
String goto_which = getIntent().getStringExtra("goto_which");
String chatUser = getIntent().getStringExtra("user_id");
if (goto_which.equals("chatactivity")) {
Intent chatIntent = new Intent(getBaseContext(), ChatActivity.class);
chatIntent.putExtra("user_id", chatUser);
startActivity(chatIntent);
} else if (goto_which.equals("grpchatactivity")) {
Intent chatIntent = new Intent(getBaseContext(), GroupChatActivity.class);
chatIntent.putExtra("group_id", chatUser);
startActivity(chatIntent);
}
}