无法使用FCM向多个设备发送通知

时间:2016-12-13 07:15:14

标签: php android firebase firebase-cloud-messaging

我只在一台设备中收到通知,该设备被设置为mySQL DB中存储该表的第一个令牌,并且通知不会发送到其余的令牌号码。我尝试了一个public Data(double[] array) { sets = new ArrayList<Double>(Arrays.asList(array)); } public String toString() { return sets.toString(); } 循环并将令牌数存储在一个数组中,但它没有用。

请提出解决方案。谢谢。

这是我的代码:

enter image description here

WHILE

4 个答案:

答案 0 :(得分:2)

使用'registration_ids'而不是'to'并传递逗号分隔的多个注册ID以在FCM中使用多播。最终的有效载荷应该是:

{
"registration_ids":["id1","id2",...],
  "priority" : "normal",
  "data" : {
    "title" : "Title",
    "message" : "Message to be send",
    "icon": "icon_path"
  }
}

请参阅https://developers.google.com/cloud-messaging/http-server-ref获取更多帮助

答案 1 :(得分:0)

您需要在方法中覆盖通知发送逻辑,然后启动循环&amp;在每次迭代中调用该方法将令牌和消息传递给方法。

答案 2 :(得分:0)

&#34; 请提出解决方案&#34;

我建议使用Services。您最常建议您阅读Android Studio here的文档。

有很多关于服务的内容,但目前我认为一个代码片段对您最有帮助,这里有一些代码,

创建一个名为 HelloService

的类

并使用正确的导入*

粘贴以下代码
public class HelloService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;

// Handler that receives messages from the thread
 private final class ServiceHandler extends Handler {
  public ServiceHandler(Looper looper) {
      super(looper);
  }
  @Override
  public void handleMessage(Message msg) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      try {
          Thread.sleep(5000);
      } catch (InterruptedException e) {
          // Restore interrupt status.
          Thread.currentThread().interrupt();
      }
      // Stop the service using the startId, so that we don't stop
      // the service in the middle of handling another job
      stopSelf(msg.arg1);
  }
}

@Override
public void onCreate() {
// Start up the thread running the service.  Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block.  We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
        Process.THREAD_PRIORITY_BACKGROUND);
thread.start();

// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
   Toast.makeText(this, "servicestarting",Toast.LENGTH_SHORT).show();


  Message msg = mServiceHandler.obtainMessage();
  msg.arg1 = startId;
  mServiceHandler.sendMessage(msg);

  // If we get killed, after returning from here, restart
  return START_STICKY;
      }

@Override
public IBinder onBind(Intent intent) {
   // We don't provide binding, so return null
   return null;
          }


 @Override
 public void onDestroy() {
   Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
 }
}

&#34;这是过度喧嚣&#34;你可能会想到自己。然而,恰恰相反。

服务+ Firebase示例

不要从Firebase推送消息,而是说您希望在您的某个数据库中进行修改时通知用户

首先,在Oncreate上创建数据库引用

mDatabaseLike=FirebaseDatabase.getInstance().getReference().child("Likes"); 

转到&#39; handleMessage方法&#39;并添加以下

      @Override
    public void handleMessage(Message msg) {



        mDatabaseLike.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

             notifyUserOfDBupdate()


            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });




        //stopSelf(msg.arg1);
    }
}

这是notifyUserOfDBupdate方法以及如何通知用户

   private void notifyUserOfDBupdate() {
    //Intents
    Intent Pdf_view = new Intent(this, //class to throw the user when they hit on notification\\.class);
    PendingIntent pdf_view = PendingIntent.getActivity(this, 0, Pdf_view, 0);


    //Notification Manager
    NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);


    //The note
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Notification noti = new NotificationCompat.Builder(getApplicationContext())
            .setTicker("TickerTitle")
            .setContentTitle("content title")
            .setSound(soundUri)
            .setContentText("content text")
            .setContentIntent(pdf_view).getNotification();


    //Execution
    noti.flags = Notification.FLAG_AUTO_CANCEL;
    nm.notify(0, noti);
}

现在在您的真实设备上运行您的应用程序一次,在模拟器上再次运行您的应用程序。一旦两个中的任何一个修改了您的firebase数据库,另一个将立即得到通知。

在HandleMessage方法中修改您喜欢的任何方法。它将是永恒的,除非你让它变得可以杀死。

最亲切的问候

答案 3 :(得分:0)

//////////////////////    FCM  START      /////////////////////////

  $path_to_fcm = "https://fcm.googleapis.com/fcm/send";

  $server_key = "your_server_key";

  $headers = array(
    'Authorization:key=' . $server_key, 
    'Content-Type:application/json');


  $keys = ["key_1", "key_2"];

  $fields = array(
    "registration_ids" => $keys,
    "priority" => "normal",
    'notification' => array(
          'title' => "title of notification",
          'body' => "your notification goes here" 
         )
       );

   $payload = json_encode($fields);


  $curl_session = curl_init();

  curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
  curl_setopt($curl_session, CURLOPT_POST, true);
  curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);

  $curl_result = curl_exec($curl_session);

//////////////////////    FCM  END      /////////////////////////

这适合我。