简体   繁体   English

Android中的Firebase推送通知无法正常工作

[英]Firebase push notification in android not working correctly

I am developing an Android application in which I am using Firebase push notifications. 我正在开发一个使用Firebase推送通知的Android应用程序。 Everything is working fine but only one issue with Firebase push notifications. 一切正常,但Firebase推送通知只有一个问题。

When my application is open then only big image notification appear ( screenshot ). 当我的应用程序打开时,只有大图像通知出现( 屏幕截图 )。

But when my application is closed the big image notification is not displaying ( screenshot ). 但是,当我的应用程序关闭时,大图像通知不会显示( 屏幕截图 )。

MyFirebaseInstanceIDService.java 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 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;
        }
    }
}

You may get mybitmap null. 您可能会得到mybitmap null。 Try to check it first and to resolve this use Picaso with the async task to download an image from url and then in on completion generate the notification with mybitmap. 尝试先检查它并解决此问题,将Picaso与async任务一起从url下载图像,然后在完成时使用mybitmap生成通知。

Hope this will help you. 希望这会帮助你。

I am also getting the same problem while using firebase. 使用Firebase时,我也遇到相同的问题。 The answer is very simple. 答案很简单。

1) Register your application on Firebase console and import the necessary library needed. 1)在Firebase控制台上注册您的应用程序,然后导入所需的必要库。

2)Make services classes MyFirebaseMessagingService and FirebaseInstanceIdService. 2)制作服务类MyFirebaseMessagingService和FirebaseInstanceIdService。

3)Register your service to AndroidManifest 3)将您的服务注册到AndroidManifest

4) Now come to MyFirebaseMessagingService.java class and do the modification 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) Make sure that you were sending your notification using post menthod without sending the notification part and sending only data part with all the header with Content-Type application/json Authorization key=yourkey link where you have to post https://fcm.googleapis.com/fcm/send with body like this 5)确保您使用后方法发送通知,而不发送通知部分,并且仅发送带有Content-Type application / json Authorization key = yourkey链接的所有标头的数据部分,您必须在其中张贴https:// fcm。 googleapis.com/fcm/与正文一起发送

 {
      "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"
       }
    } 

now click send and this will work. 现在,点击发送即可。 already tested 已经测试过

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM