【问题标题】:Firebase push notification in android not working correctlyandroid中的Firebase推送通知无法正常工作
【发布时间】:2018-06-01 08:55:32
【问题描述】:

我正在开发一个使用 Firebase 推送通知的 Android 应用程序。一切正常,但 Firebase 推送通知只有一个问题。

当我的应用程序打开时,只会出现大图通知 (screenshot)。

但是当我的应用程序关闭时,大图通知不显示 (screenshot)。

MyFirebaseInstanceIDService.java

 public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
        private static final String TAG = "MyFirebaseIIDService";
        @Override
        public void onTokenRefresh() {
            // Get updated InstanceID token.
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            Log.d(TAG, "Refreshed token: " + refreshedToken);
            sendRegistrationToServer(refreshedToken);
        }
        private void sendRegistrationToServer(String token) {
        }
    }

MyFirebaseMessagingService.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FirebaseMessageService";
    Bitmap bitmap;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

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

        //The message which i send will have keys named [message, image, AnotherActivity] and corresponding values.
        //You can change as per the requirement.

        //message will contain the Push Message
        String message = remoteMessage.getData().get("message");
        //imageUri will contain URL of the image to be displayed with Notification
        String imageUri = remoteMessage.getData().get("image");
        //If the key AnotherActivity has  value as True then when the user taps on notification, in the app AnotherActivity will be opened.
        //If the key AnotherActivity has  value as False then when the user taps on notification, in the app MainActivity will be opened.
        String TrueOrFlase = "praveen";

        //To get a Bitmap image from the URL received
        bitmap = getBitmapfromUrl(imageUri);

        try {
//            BitmapFactory.decodeResource(getResources(), R.drawable.watchicon)
            sendNotification(message,bitmap , TrueOrFlase);
        } catch (Exception e) {
            Log.e("qwerty", " exception = " + e.toString());
        }

    }


    /**
     * Create and show a simple notification containing the received FCM message.
     */

    private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) {
        Intent intent = new Intent(getApplicationContext(), StartActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("AnotherActivity", TrueOrFalse);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.ball)
                .setContentTitle(messageBody)
                .setContentText("hello")
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(image))
                .setAutoCancel(true);


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

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());


    }

    /*
     *To get a Bitmap image from the URL received
     * */
    public Bitmap getBitmapfromUrl(String imageUrl) {

        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

【问题讨论】:

  • 你是如何发送推送通知的?,使用 Firebase 控制台还是你打个电话?
  • 是的,来自 Firebase 控制台
  • 好的,问题是当应用程序没有运行时,firebase 会自行处理消息 [如果您从控制台发送消息]。如果您将日志放入 onMessageReceived,确保您在发送通知后不会收到它们。为了解决这个问题,您必须使用 firebase api 来完成这项工作。通常firebase通知有两个组件,数据和通知。为了使您的用例正常工作,您必须将通知部分发送为 null 并传递您需要在数据部分中呈现的所有内容。这样你就可以通过解析数据得到你需要渲染的任何东西
  • 您是说如果我要通过 post 方法使用 firebase api 发送通知,即使我的活动已关闭,它也能正常工作?
  • 是的,前提是您确保将通知部分发送为 null 并使用数据部分处理通知

标签: android android-notifications


【解决方案1】:

我在使用 firebase 时也遇到了同样的问题。答案很简单。

1) 在 Firebase 控制台上注册您的应用程序并导入所需的必要库。

2) 将服务类设为 MyFirebaseMessagingService 和 FirebaseInstanceIdService。

3)将您的服务注册到 AndroidManifest

4) 现在来到 MyFirebaseMessagingService.java 类并进行修改

public class Notif extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            try {
                JSONObject data = new JSONObject(remoteMessage.getData());
                String jsonMessage = data.getString("body");
                String jsonTitle = data.getString("title");
                String jsonImage = data.getString("image");
                mainNotification(jsonTitle, jsonMessage, jsonImage);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void mainNotification(String title, String body, String image) {
        Intent i = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder bn = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.analytics)
                .setContentTitle(title)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
                .setContentText(body)
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(getBitmapfromUrl(image)))
                .setAutoCancel(true)
                .setContentIntent(pi);
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (nm != null)
            nm.notify(0, bn.build());
    }


    public Bitmap getBitmapfromUrl(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(input);
            return bitmap;

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}

5) 确保您使用 post menthod 发送通知,而不发送通知部分,并且仅发送 data 部分和所有 带有 Content-Type application/json 的标头 授权密钥=您的密钥 您必须发布的链接https://fcm.googleapis.com/fcm/send 像这样的身体

 {
      "to": "/topics/NEWS",
       "data": {
           "body":"text",
           "title":"AAAAAAA",
           "image":"https://static.independent.co.uk/s3fs-public/styles/article_small/public/thumbnails/image/2016/11/14/12/messi.jpg"
       }
    } 

现在单击发送,这将起作用。已经测试过了

【讨论】:

    【解决方案2】:

    您可能会得到 mybitmap 为空。尝试先检查它并解决此问题,使用 Picaso 和异步任务从 url 下载图像,然后在完成时使用 mybitmap 生成通知。

    希望这会对你有所帮助。

    【讨论】:

    • 即使小图标不可见,也可以看到它们的图像
    猜你喜欢
    • 2016-06-19
    • 2021-08-09
    • 2022-12-16
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多