【问题标题】:How to send push notification on button click如何在按钮单击时发送推送通知
【发布时间】:2017-12-06 18:33:38
【问题描述】:

我已经为我的 android 应用程序创建了推送通知,当我尝试从 firebase 控制台发送它时它就可以工作了。现在我想要的是当用户点击注册时发出推送通知,然后向其他用户显示通知。

我在 google 中搜索过,但没有找到示例之一。目标是通知其他用户我的应用中有新用户注册。

感谢您的帮助

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMessagingService";
    public static final int ID_SMALL_NOTIFICATION = 235;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        // TODO(developer): Handle FCM messages here.

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification("Hi ini isinya");
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG,"Message Notification Title" + remoteMessage.getNotification().getTitle());
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, ID_SMALL_NOTIFICATION, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = "fcm_default_channel";
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.icon)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(ID_SMALL_NOTIFICATION, notificationBuilder.build());
    }

}

【问题讨论】:

    标签: android json push-notification onclick android-volley


    【解决方案1】:

    我没明白你的意思,但你可以使用 Volly Json 对象请求

    首先您需要从 Firebase 控制台复制您的 服务器密钥,打开 Firebase Console 并选择您的项目

    第二次在你的项目中添加 Volley 依赖

    编译'com.mcxiaoke.volley:library:1.0.19'

    那么你可以添加这个代码来推送

    private void sendFCMPush() {
    
                String SERVER_KEY = YOUR_SERVER_KEY;
                String msg = "this is test message";
                String title = "my title";
                String token = FCM_TOKEN;
    
                JSONObject obj = null;
            JSONObject objData = null;
            JSONObject dataobjData = null;
    
            try {
                obj = new JSONObject();
                objData = new JSONObject();
    
                objData.put("body", msg);
                objData.put("title", title);
                objData.put("sound", "default");
                objData.put("icon", "icon_name"); //   icon_name
                objData.put("tag", token);
                objData.put("priority", "high");
    
                dataobjData = new JSONObject();
                dataobjData.put("text", msg);
                dataobjData.put("title", title);
    
                obj.put("to", token);
                //obj.put("priority", "high");
    
                obj.put("notification", objData);
                obj.put("data", dataobjData);
                Log.e("return here>>", obj.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
    
                JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, Constants.FCM_PUSH_URL, obj,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                Log.e("True", response + "");
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.e("False", error + "");
                            }
                        }) {
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("Authorization", "key=" + SERVER_KEY);
                        params.put("Content-Type", "application/json");
                        return params;
                    }
                };
                RequestQueue requestQueue = Volley.newRequestQueue(this);
                int socketTimeout = 1000 * 60;// 60 seconds
                RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                jsObjRequest.setRetryPolicy(policy);
                requestQueue.add(jsObjRequest);
    }
    

    希望有帮助

    【讨论】:

    • 试过这段代码,但在任何设备上都没有收到通知,有什么解决办法吗?
    • 您遇到什么错误?永远不会收到通知是什么意思?
    • 我把代码放在我的mainactivity中,当尝试点击注册按钮时在任何设备上都没有通知,请帮忙
    • 你换过token吗? FCM_TOKEN 与您的设备令牌?
    【解决方案2】:

    当一个用户点击注册时,您想向所有已经注册的其他人发送推送,对吧? 您需要向该地址发出 HTTP POST 请求:

    https://fcm.googleapis.com/fcm/send
    

    带有一个名为“Authorization”的标头,其值类似于“key=AIza...”。

    因此,在请求正文中,您可以像这样发送 JSON。

    {
      "to": "/topics/foo-bar",
      "data": {
        "message": "This is a Firebase Cloud Messaging Topic Message!",
       }
    }
    

    然后您需要创建一个主题并将设备订阅到相同的主题。

    FirebaseMessaging.getInstance().subscribeToTopic("foo-bar");
    

    应该没问题。

    【讨论】:

    • 那么我需要在哪里添加这些代码?在 android 应用项目或 php 文件中?
    • 当你的用户点击注册时,你应该注册他并并行做一个HTTP请求
    • 我可以告诉你需要做什么,然后你就向前看。好的?不粗鲁。您需要使用 AsyncTask 或使用 Retrofit 来发出 HTTP 请求。 stackoverflow 中有很多例子。
    • 还是没有得到解决,我应该在android中使用HTTP请求添加什么代码?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 2017-04-18
    • 2023-03-04
    相关资源
    最近更新 更多