如何使用PHP和Android解决与错误相关的发送和接收壁炉通知?

发布于 2025-02-12 22:09:04 字数 3857 浏览 1 评论 0原文

我想从后端向Firebase发送通知,以及在Android应用程序上接收什么。

我遵循的步骤

  1. 设置一个Android客户端并获取当前令牌并将其存储在 后端如下播种

      private void getToken(){
        firbasemessaging.getInstance()。getToken()
                。
                    @Override
                    public void oncomplete(@nonnull任务< string> task){
                        如果(!task.issuccessful()){
                            log.w(标签,“获取FCM注册令牌失败”,task.getException());
                            返回;
                        }
                        //获取新的FCM注册令牌
                        字符串令牌= task.getResult();
                        log.w(标签,“ FCM注册令牌”,task.getException());
                        //功能将其存储在后端服务器上
                        settoken(user_name,doken);
    
                    }
                });
    }
     

  1. 写下php代码以发送消息

     函数send_notification($ msg,$ user_id)
    {
      $ title ='alert'; 
      $ user_token = null;
      //获取查询以从数据库获取令牌
      $ this-> db-> select('token');
      $ this-> db->来自('tbl_user_token');
      $ this-> db-> where('user_id',$ user_id);
      $ user_check = $ this-> db-> get();
      if($ user_check-> num_rows()> 0){ 
         foreach($ user_check-> result()as $ row)
          {
            $ user_token = $ row-> token;
            $ wendesp [“ user_token”] = $ user_token;
            $ url ='https://fcm.googleapis.com/fcm/send';
            $ apikey = 'AAAAQJWVS6Q:APA91BHA-M01WCK3GMN6PLN8OQDGKVNGMVQ7TLXY6RMDMU4IYYYYNDCGROYVDPFRBE mt_pnzzajo2jmw4wemylxn5dspw-pp7766iwztmr1bxhc7r6uiym9_iq7utocjyb1w1lvmxpak';
    $ headers = array('授权:key ='。$ apikey,
                    '内容类型:应用程序/json'
                    );
    $ notifdata = [
      'title'=> $ title,
      'Body'=> $ msg
    ];
    
    $ notifbody = [
      'Notification'=> $ notifdata,
      'time_to_live'=> 3600,
      'to'=> $ user_token
    ];
    
    $ ch = curl_init();
    curl_setopt($ ch,curlopt_url,$ url);
    curl_setopt($ ch,curlopt_post,true);
    curl_setopt($ ch,curlopt_httpheader,$ headers);
    curl_setopt($ ch,curlopt_postfields,json_encode($ notifbody));
    $结果= curl_exec($ ch);
    $ noti_data = array('sender'=> $ user_token,'title'=> $ title,'message'=> $ msg);
    //插入查询以在后端保存通知
    $ insert = $ this-> db-> insert('tbl_notifications',$ noti_data);
    打印($ result);
    curl_close($ ch);     
    }
    }
    返回$响应;   
    }
     

    它已成功地在数据库中插入了通知详细信息,如下所示

    “在此处输入图像描述”

  2. 编写代码以从Android应用中的Firebase接收通知,如下所示

      @Override
    public void onMessageReceived(@nonnull remotemessage消息){
    //为您的应用中的活动创建明确的意图
       意图意图=新意图(this,mainActivity.class);
       intent.setFlags(intent.flag_activity_new_task | intent.flag_activity_clear_task);
       pendingIntent pendentIntent = pendingIntent.getActivity(this,0,intent,pendingIntent.flag_immutable);
    
       NotificationCompat.builder Builder = new NotificationCompat.builder(this,“ 101”)
            .setsmallicon(r.drawable.ic_baseline_notifications_24)
            .setContentTitle(message.getNotification()。getTitle())
            .setContentText(message.getNotification()。getBody())
            .setPriority(notificationcompat.priority_default)
            //设置用户点击通知时发射的意图
            .setContentintent(pendentintent)
            .setautaCancel(true);
    
    NotificationManagerCompat NotificationManager = NotificationManagerCompat.from(this);
    // NotificationID是您必须定义的每个通知的唯一INT
    notificationmanager.notify(1,builder.build());
    }
     

它没有任何错误,但没有显示任何通知,为什么?

为此,我遵循下面给出的YouTube视频

https:///www.youtube.com/watch? V = 6CMDHSVL89E

I want to send a notification to firebase from the backend and what to receive it on the android app.

Steps which I have followed

  1. Set up an android client and fetch the current token and store it on
    backend as sown below

    private void getToken() {
        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(@NonNull Task<String> task) {
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
                            return;
                        }
                        // Get new FCM registration token
                        String token = task.getResult();
                        Log.w(TAG, "FCM registration token ", task.getException());
                        //function store it on backend server
                        setToken(user_name,token);
    
                    }
                });
    }
    

enter image description here

  1. Wrote PHP code to send messages

    function send_notification($msg,$user_id)
    {
      $title = 'Alert'; 
      $user_token = null;
      //fetch query to fetch token from database
      $this->db->select('token');
      $this->db->from('tbl_user_token');
      $this->db->where('user_id',$user_id);
      $user_check=$this->db->get();
      if($user_check->num_rows() >0){ 
         foreach($user_check->result() as $row)
          {
            $user_token = $row->token;
            $response["user_token"]=$user_token;
            $url = 'https://fcm.googleapis.com/fcm/send';
            $apiKey = 'AAAAQjWvs6Q:APA91bHa-M01wCK3GmN6PLN8oqDgKvNGmVq7TlXy6rMdMU4IYYNDcgroYvDPfRBemT_pNZZAJo2jmw4wemYlXN5DsPW-pP7766IWZTMR1BxhC7r6uIYM9_IQ7UtoCocjyb1W1LvMxPak';
    $headers = array('Authorization:key='.$apiKey,
                    'Content-Type:application/json'
                    );
    $notifData = [
      'title'=>$title,
      'body'=>$msg
    ];
    
    $notifBody = [
      'notification'=>$notifData,
      'time_to_live'=>3600,
      'to'=> $user_token
    ];
    
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($notifBody));
    $result = curl_exec($ch);
    $noti_data = array('sender'=>$user_token,'title'=>$title,'message'=>$msg);
    //insert query to save notifications in the backend
    $insert  = $this->db->insert('tbl_notifications', $noti_data);
    print($result);
    curl_close($ch);     
    }
    }
    return $response;   
    }
    

    It has successfully inserted notifications details in the database as shown below

    enter image description here

  2. Wrote code to receive notification from the firebase in android app as shown below

    @Override
    public void onMessageReceived(@NonNull RemoteMessage message) {
    // Create an explicit intent for an Activity in your app
       Intent intent = new Intent(this, MainActivity.class);
       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
       PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
    
       NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "101")
            .setSmallIcon(R.drawable.ic_baseline_notifications_24)
            .setContentTitle(message.getNotification().getTitle())
            .setContentText(message.getNotification().getBody())
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);
    
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    // notificationId is a unique int for each notification that you must define
    notificationManager.notify(1, builder.build());
    }
    

It does not have any errors but it does not show any notifications, why?

I followed the youtube video given below for this purpose

https://www.youtube.com/watch?v=6CMdHsVl89E

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北方的巷 2025-02-19 22:09:04

您是否在 subtest.xml 上注册了 service.class ,还检查服务器的结果!

  • 清楚
<service
   android:name=".CLASS"
   android:exported="false">
   <intent-filter>
      <action android:name="com.google.firebase.MESSAGING_EVENT" />
   </intent-filter>
</service>
  • 这就是我的做法,尝试显示 推送通知 使用此...
public class PushNotification {

    // Notification manager
    private NotificationManager notificationManager;
    // Main title of the notification
    private String notificationTitle;
    private String notificationMessage;
    private final Context mContext;

    public PushNotification(Context mContext) {
        this.mContext = mContext;
    }

    public void setNotificationTitle(String title) {
        this.notificationTitle = title;
    }

    public void setNotificationMessage(String message){
        this.notificationMessage = message;
    }

    public void pushNotificationMessage() {
        if (notificationManager == null) {
            notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        int NOTIFICATION_ID_2 = new Random().nextInt(1000); // 150
        // Notification builder
        NotificationCompat.Builder notificationBuilder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel mChannel = notificationManager.getNotificationChannel(String.valueOf(NOTIFICATION_ID_2));
            if (mChannel == null) {
                mChannel = new NotificationChannel(String.valueOf(NOTIFICATION_ID_2), notificationTitle, importance);
                mChannel.enableVibration(true);
                mChannel.setSound(null, null);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                notificationManager.createNotificationChannel(mChannel);
            }
            notificationBuilder = new NotificationCompat.Builder(mContext, String.valueOf(NOTIFICATION_ID_2))
                    .setColor(mContext.getColor(R.color.colorPrimary))
                    .setContentTitle(this.notificationTitle) // required
                    .setSmallIcon(R.drawable.ic_shopping_bag) // required
                    .setContentText(this.notificationMessage) // required
                    .setDefaults(0)
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(this.notificationMessage))
                    .setSound(null)
                    .setAutoCancel(false)
                    .setTicker("TICKER");
            //.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        } else {
            notificationBuilder = new NotificationCompat.Builder(mContext, String.valueOf(NOTIFICATION_ID_2))
                    .setColor(mContext.getColor(R.color.colorPrimary))
                    .setContentTitle(this.notificationTitle) // required
                    .setSmallIcon(R.drawable.ic_shopping_bag) // required
                    .setContentText(this.notificationMessage) // required
                    .setDefaults(0)
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(this.notificationMessage))
                    .setSound(null)
                    .setAutoCancel(false)
                    .setTicker("TICKER")
                    //.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                    .setPriority(Notification.PRIORITY_LOW);
        }
        Notification notification = notificationBuilder.build();
        notificationManager.notify(NOTIFICATION_ID_2, notification);
    }
}

Have you registered your service.class on Manifest.xml and also check the results from your server!.

  • Manifest
<service
   android:name=".CLASS"
   android:exported="false">
   <intent-filter>
      <action android:name="com.google.firebase.MESSAGING_EVENT" />
   </intent-filter>
</service>
  • This is how i do it, Try to display Push Notification using this...
public class PushNotification {

    // Notification manager
    private NotificationManager notificationManager;
    // Main title of the notification
    private String notificationTitle;
    private String notificationMessage;
    private final Context mContext;

    public PushNotification(Context mContext) {
        this.mContext = mContext;
    }

    public void setNotificationTitle(String title) {
        this.notificationTitle = title;
    }

    public void setNotificationMessage(String message){
        this.notificationMessage = message;
    }

    public void pushNotificationMessage() {
        if (notificationManager == null) {
            notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        int NOTIFICATION_ID_2 = new Random().nextInt(1000); // 150
        // Notification builder
        NotificationCompat.Builder notificationBuilder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel mChannel = notificationManager.getNotificationChannel(String.valueOf(NOTIFICATION_ID_2));
            if (mChannel == null) {
                mChannel = new NotificationChannel(String.valueOf(NOTIFICATION_ID_2), notificationTitle, importance);
                mChannel.enableVibration(true);
                mChannel.setSound(null, null);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                notificationManager.createNotificationChannel(mChannel);
            }
            notificationBuilder = new NotificationCompat.Builder(mContext, String.valueOf(NOTIFICATION_ID_2))
                    .setColor(mContext.getColor(R.color.colorPrimary))
                    .setContentTitle(this.notificationTitle) // required
                    .setSmallIcon(R.drawable.ic_shopping_bag) // required
                    .setContentText(this.notificationMessage) // required
                    .setDefaults(0)
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(this.notificationMessage))
                    .setSound(null)
                    .setAutoCancel(false)
                    .setTicker("TICKER");
            //.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        } else {
            notificationBuilder = new NotificationCompat.Builder(mContext, String.valueOf(NOTIFICATION_ID_2))
                    .setColor(mContext.getColor(R.color.colorPrimary))
                    .setContentTitle(this.notificationTitle) // required
                    .setSmallIcon(R.drawable.ic_shopping_bag) // required
                    .setContentText(this.notificationMessage) // required
                    .setDefaults(0)
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(this.notificationMessage))
                    .setSound(null)
                    .setAutoCancel(false)
                    .setTicker("TICKER")
                    //.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                    .setPriority(Notification.PRIORITY_LOW);
        }
        Notification notification = notificationBuilder.build();
        notificationManager.notify(NOTIFICATION_ID_2, notification);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文