получаю ошибку при отправке push уведомления через свой сервис и через свой скрипт на сайте
FCM сообщения не приходят. (при выполнении метода Send_Notification) Получаю такую ошибку в Logcat при отправке push уведомления через свой сервис и через свой скрипт на сайте:
<title>Error 400 (Bad Request)!!1</title>
Имеется такой java класс сервиса:
package com.example.my_new_service_fcm;
//package com.protocoderspoint.sendingpushnotificationusingphpcode;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FirebaseCloudMessagingServices extends FirebaseMessagingService {
public FirebaseCloudMessagingServices() {
}
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle(); // will hold FCM Title
String message = remoteMessage.getNotification().getBody(); //will hold FCM message body
sendNotification(title,message);
}
}
private void sendNotification(String title, String message) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "admin_channel_1";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = getNotificationChannel(NOTIFICATION_CHANNEL_ID);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
notificationBuilder.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
//.setPriority(Notification.PRIORITY_MAX)
.setContentTitle(title)
.setContentText(message);
notificationManager.notify(1, notificationBuilder.build());
}
@NonNull
private static NotificationChannel getNotificationChannel(String NOTIFICATION_CHANNEL_ID) {
@SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Sample Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
return notificationChannel;
}
}
и майн активити:
package com.example.my_new_service_fcm;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.messaging.FirebaseMessaging;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.my_new_service_fcm.databinding.ActivityMainBinding;
import com.google.firebase.messaging.FirebaseMessaging;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
Spinner spinnerTopic;
Button subscribe,send_Pushnotification;
// this link is my server where my php script for push notification exist
String URL_NOTI="https://spektr-ekb.ru/push_notification.php";
String topic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// setSupportActionBar(binding.toolbar);
// NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
// appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
// NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
FirebaseMessaging.getInstance().subscribeToTopic("Gadgets");
spinnerTopic = (Spinner)findViewById(R.id.spinner);
subscribe=(Button)findViewById(R.id.subscribe);
send_Pushnotification=(Button)findViewById(R.id.getnotified);
subscribe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
topic = spinnerTopic.getSelectedItem().toString();
System.out.println(topic);
//subscribing yourself to topic you have selected from spinner
FirebaseMessaging.getInstance().subscribeToTopic(topic);
Toast.makeText(MainActivity.this,"Subscribed successfully to: "+topic,Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,"Now just Hit Notify me Button "+topic,Toast.LENGTH_SHORT).show();
}
});
send_Pushnotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Send_Notification(topic);
}
});
}
private void Send_Notification(final String topic)
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_NOTI,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("farmerorderdataresponse",response);
try{
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Login Error !1"+e,Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Login Error !2"+error,Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String, String> getParams() {
Map<String,String> params = new HashMap<>();
params.put("title","Order Received");
params.put("body","This is a notification");
params.put("topic","Gadgets");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
//Toast.makeText(getApplicationContext(),"Logfgfgfgfg1",Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
}
и скрипт на сайте:
<?php
$user= $_POST['topic'];
$title = $_POST['title'];
$body = $_POST['body'];
$url = "https://fcm.googleapis.com/fcm/send";
$topic = "/topics/$user";
//replace serverkey with your firebase console project server key
$serverKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCgFlhGhOWapURi\nAX41GpnxjVrz6mAB5djLmDIWXJdKo7jjWTwFRAt+ScotfTrFp+KnDdkb9Z8bj+1V\nfFMq531284bBpJ9iZCgauYJSZlStk/rXKULLzRHGlNLkHMmvqo0i1ovsCjeP6HRx\n0sw8DlvRdiyDNaO4Iwk8/Qh/187YcJarmGd5Of+LdH8KmgPn0cp4ZhUgfpQitcF+\ntJ97o943j+c7Z2UretiLDjXNqRpHRP9MsNd/TX8FYDnGubw8odtrjswgTQRI2gp1\nW5oeT4jgjqT7elCCAsdx5GCXExgNbIwuUEXcNElLoVdeJ2RndIcE+EYHSXUujoZf\nT0Ksr5jJAgMBAAECggEAFfhjFpCEG1htnV6zlbGoKXa7IgkLMo97FJv3WcrMx6VX\nCTqUqmtXgXY6jUonv/slt8QGhRgNRUDYM1h76II7HZFX7+j6J8xzlZFakZjyK51I\nunEy9dnXw+9mTwClbFqlgn+71cHkNLeUDY/+0Aovbzx+6OX6aVnDmY9ndHYncNwx\nOgryKBYu/9VRF5+n5B4hTsH+f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$body = '$_POST['body']';
// $intent_filter=$action;
$notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $topic, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
?>
код генерироваол на console.cloud.google.com во вкладке firebase-adminsdk -> keys Скажите, почему возникает ошибка?