Я работаю над приложением чата android, использующим Firebase. Все отлично работает, кроме pu sh уведомления. Я погуглил и прочитал почти каждый пост, касающийся проблемы, но все еще не нашел решение!
Проблема: На бесплатной sh установке приложения на устройство! Я получаю уведомление (ТОЛЬКО ОДИН РАЗ В ПЕРВЫЙ РАЗ), после чего уведомление не отображается вообще. Залп возвращает сообщение об успешном завершении «Идентификатор многоадресной передачи остается неизменным для каждого успешного сообщения, и даже идентификатор сообщения остается неизменным для каждого успешного сообщения», удивляясь, что это связано с проблемой! Посмотрите на приведенный ниже код:
1) МОЙ PHP СЦЕНАРИЙ НА СВОЕМ СВОЕМ АДРЕСЕ (APP-СЕРВЕР):
<?php
define( 'API_ACCESS_KEY', 'AAAAeaFcZdA:APA91bFqhLc..............' );
$token = $_GET["token"];
$title = $_POST["title"];
$notification = $_POST["message"];
$msg =
[
'message' => $notification,
'title' => $title,
];
$fields =
[
'to' => $token,
'data' => $msg
];
$headers =
[
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close( $ch );
echo $result;
?>
2) Мой MessagingService (Firebase) для получать уведомления, так как я получаю первое уведомление, я считаю, что оно настроено правильно!
public class MessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Timber.i("From: " + remoteMessage.getFrom());
//Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Timber.i("Message data payload: " + remoteMessage.getData());
Map<String, String> data = remoteMessage.getData();
sendNotification(data);
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Timber.i("Message Notification Body: " + remoteMessage.getNotification().getBody());
Map<String, String> data = remoteMessage.getData();
sendNotification(data);
}
Map<String, String> data = remoteMessage.getData();
sendNotification(data);
}
@Override
public void onNewToken(@NonNull String token) {
Timber.i("MyToken: " + token);
sendRegistrationToServer(token);
}
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference usersdRef = database.getReference("users");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
usersdRef.child(user.getUid()).child("tokens").setValue(token);
}
}
private void sendNotification(Map<String, String> messageBody) {
String myTitle = messageBody.get("title");
final int not_nu = generateRandom();
Intent intent = new Intent(this, ChatMessageActivity.class);
intent.putExtra("username", myTitle);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ChatUserModel.chatWith = myTitle;
PendingIntent pendingIntent = PendingIntent.getActivity(this, not_nu /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.marker)
.setContentTitle(messageBody.get("title"))
.setContentText(messageBody.get("message"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(not_nu /* ID of notification */, notificationBuilder.build());
}
public int generateRandom() {
Random random = new Random();
return random.nextInt(9999 - 1000) + 1000;
}}
3) Моя активность в чате, когда я отправляю сообщение другому пользователю. getOtherToken = идентификатор другого токена пользователя, которому я отправлю сообщение
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String messageText = messageArea.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("dd.MMM.yyyy", Locale.getDefault());
String currentDate = sdf.format(new Date());
String currentTime = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
if (!messageText.equals("")) {
Map<String, String> map = new HashMap<String, String>();
map.put("message", messageText);
map.put("user", user.getDisplayName());
map.put("timetoshow", currentTime);
map.put("dateStamp", currentDate);
usersmRef.child(reference1).push().setValue(map);
usersmRef.child(reference2).push().setValue(map);
messageArea.setText("");
sendNotificationToappServer(getOtherToken, user.getDisplayName(), messageText);
Timber.i("GetOtherTOken: " + user.getDisplayName() + " | " + getOtherToken + " | " + messageText);
}
}
});
4) Мой метод залпа в той же функции ChatActivity. java как указано выше, где я отправляю запрос строки на мой сервер приложений, токен здесь от пользователя, который получит сообщение!
public void sendNotificationToappServer(String token, String title, String notification) {
String SERVER_ADDRESS = "https://www.mywebsite/notification.php?token=";
RequestQueue requestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
requestQueue = new RequestQueue(cache, network);
// Start the queue
requestQueue.start();
StringRequest stringRequest = new StringRequest(Request.Method.POST, SERVER_ADDRESS + token,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(ChatMessageActivity.this, response, Toast.LENGTH_LONG).show();
Timber.i("Volley: %s", response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ChatMessageActivity.this, error.toString(), Toast.LENGTH_LONG).show();
Timber.i("Volley Error: " + error.toString());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("title", title);
params.put("message", notification);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
requestQueue.add(stringRequest);
}
5) Мой залповый ответ записан в Android Studio, что успешно, Впервые он доставляет уведомление pu sh, но не после что до fre sh установить!
Все, что требуется, если не указано выше! пожалуйста, дайте мне знать. Скрестим пальцы!