web-dev-qa-db-ja.com

Firebaseプッシュ通知-通知に複数行メッセージを表示する方法

プッシュ通知のmessageの1行だけで取得します。一方、multiple lines with BigPictureStyleおよびBase(両方の通知スタイル)。

添付のScreenshotを参照してください。この画像では、"Hello from Firebase Cloud Messaging"したがって、これは単一行自体に収まります。

しかし、実際には、「Firebase Cloud Messagingからこんにちは、またFirebase Cloud Messagingからこんにちは」を表示しようとすると、それでもsingle line only3つのドットを最後にこのように...

enter image description here

codeに必要なpartは次のとおりです、私は使用しています:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setLargeIcon(image)/*Notification icon image*/
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(image)
                        .setBigContentTitle(messageTitle)
                        .setSummaryText(Html.fromHtml(messageBody)
                        .toString()))/*Notification with Image*/
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

注:同じ問題、私はいつでも直面しています、大きな画像なしでメッセージを送信しています(ベース/シンプルプッシュ通知)

こちらをご覧くださいscreenshot

enter image description here

したがって、唯一の懸念事項は、Notificationで複数行メッセージを表示する方法?です。

14
Sophie

ほとんどありました。 bigText プロパティを設定するだけです。

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setAutoCancel(true);

    NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
    bigTextStyle.setBigContentTitle("Title");
    bigTextStyle.bigText("Lorem ipsum dolor sit amet, consectetur adipiscing elit," +
            " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " +
            "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris " +
            "nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in.");

    notificationBuilder.setStyle(bigTextStyle);

    NotificationManager mNotifyMgr = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);
    mNotifyMgr.notify(1, notificationBuilder.build());

multiline

11
Dus

独自のレイアウトを使用する必要があります。

Builder builder = new Builder(context);
builder.setSmallIcon(R.drawable.star_white)
builder.setAutoCancel(true)
builder.setContentIntent(pendingIntent);
builder.setPriority(NotificationCompat.PRIORITY_MAX);

RemoteViews remoteViewsBig = new RemoteViews(context.getPackageName(), R.layout.notification_big);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_small);
remoteViewsBig.setImageViewBitmap(R.id.banner, bitmap);

remoteViewsBig.setTextViewText(R.id.button, data.getButtonText());
remoteViews.setTextViewText(R.id.button, data.getButtonText());

remoteViewsBig.setTextViewText(R.id.text_title, data.getTitle());
remoteViews.setTextViewText(R.id.text_title, data.getTitle());

remoteViewsBig.setTextViewText(R.id.text_content, data.getContent());
remoteViews.setTextViewText(R.id.text_content, data.getContent());

builder.setCustomContentView(remoteViews);
builder.setCustomBigContentView(remoteViewsBig);

NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());

そしてxmlファイル:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
              xmlns:tools="http://schemas.Android.com/tools"
              Android:layout_width="match_parent"
              Android:layout_height="wrap_content"
              Android:background="@color/custom_blue_gray_800"
              Android:orientation="horizontal"
    >

    <ImageView
        Android:layout_width="44dp"
        Android:layout_height="44dp"
        Android:layout_gravity="center"
        Android:src="@mipmap/ic_launcher"
        />

    <LinearLayout
        Android:layout_width="0dp"
        Android:layout_height="wrap_content"
        Android:layout_marginLeft="12dp"
        Android:layout_marginRight="12dp"
        Android:layout_weight="1"
        Android:gravity="center_vertical"
        Android:orientation="vertical"
        Android:padding="8dp"
        >

        <TextView
            Android:id="@+id/text_title"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:textColor="@Android:color/white"
            Android:textSize="16sp"
            tools:text="Title"
            />

        <TextView
            Android:id="@+id/text_content"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:textColor="@Android:color/darker_gray"
            Android:textSize="14sp"
            tools:text="text\ntext\ntext"
            />

    </LinearLayout >

    <Button
        Android:id="@+id/button"
        Android:layout_width="wrap_content"
        Android:layout_height="36dp"
        Android:layout_gravity="center_vertical"
        Android:background="@drawable/button_main"
        Android:text="Click"
        Android:textColor="@Android:color/white"
        Android:textSize="12sp"
        />

</LinearLayout >

そして

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
              xmlns:app="http://schemas.Android.com/apk/res-auto"
              Android:layout_width="match_parent"
              Android:layout_height="wrap_content"
              Android:background="@color/custom_blue_gray_800"
              Android:orientation="vertical"
              Android:paddingLeft="12dp"
              Android:paddingRight="12dp"
              Android:paddingBottom="12dp"
    >

    <include layout="@layout/notification_small" />

    <ImageView
        Android:id="@+id/banner"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        Android:adjustViewBounds="true"
        Android:scaleType="centerCrop"
        />


</LinearLayout >
4
mac229

これを試して:-

NotificationCompat.Builder builder = new NotificationCompat.Builder(
        context);
Notification notification = builder.setContentIntent(contentIntent)
        .setSmallIcon(icon).setTicker(appname).setWhen(0)
        .setAutoCancel(true).setContentTitle(appname)
        .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
        .setContentText(message).build();

notificationManager.notify(0, notification);
3
Nikhil Jadhav

@Dus answer ...を使用して複数行を表示できますが、bigPictureSyleを使用すると、setSummaryTextメソッドに常に単一行があり、他のオプションはRemoteViewを作成し、必要な設計に従ってUIを実装します

RemoteViewを参照- this を参照

2

これがあなたに使用されることを望みます。これをチェックして:

   NotificationCompat.Builder builder = new NotificationCompat.Builder(
            context);
    Notification notification = builder.setContentIntent(contentIntent)
            .setSmallIcon(icon).setTicker(appname).setWhen(0)
            .setAutoCancel(true).setContentTitle(appname)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
            .setContentText(message).build();

    notificationManager.notify(0, notification);

このリンクを参照してください: 複数行で通知を表示

ありがとうございました...

2
vicky mahale

これは、通知で大きな画像と複数行のテキストを表示する方法です。これは私のプロジェクトで動作するコードです。

Fcmには2種類のfcmメッセージがあります。 Display MessagesおよびData Messages。そして、Data Messagesフォアグラウンドおよびバックグラウンドでfcm通知を処理します。

  /**
 * Created by Mohammed Farhan on 01-08-2017.
 */

public class MyFirebaseMessagingService extends FirebaseMessagingService
{

    private static final String TAG = "MyFirebaseMsgService";
    private AppAuth auth;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage)
    {
    }




        /*To check if remoteMessage is empty, if not empty then read the id from "title" field*/
        if (remoteMessage.getData().size() > 0)
        {
            Map<String, String> data = remoteMessage.getData();
            String title = data.get("title");
            sendNotification(title);
            Log.d(TAG, title.toString());
        }

    }


    private void sendNotification(String title)
    {


        final String id = title;

        /* Here DataFromServer is custom method, used to sync data from my server. It has interface method to listen it when data sync and adding it to local sql completes*/
        DataFromServer dataFromServer = new DataFromServer(this);
        dataFromServer.setDataLoadCompleteListener(new DataLoadCompleteListener()
        {
            @Override
            public void dataLoadComplete()
            {

            /*AppNotificationDAO is a class which  has many DAO(Data Access Object) method. I have used DAO to make ease in saving,querying data from local sql*/
                AppNotificationDAO appNotificationDAO = new AppNotificationDAO(MyFirebaseMessagingService.this);

                /*getAppNotificationByID is DAO method which does server communication and fetch data from it based on Id(Here its notificationId)*/
                AppNotification appNotification = appNotificationDAO.getAppNotificationByID(Long.valueOf(id));
                if (appNotification != null)
                {
                    if (appNotification.getPhoto().equalsIgnoreCase("NA"))
                    {
                    /* photo is a field in my AppNotification class and getPhoto() is getter  and appNotification.getPhoto() returns the value stored in it. Here am using it to save url of image related to notification in my web app*/

                        /*if url is not present then below method displays just a text as notification*/
                        showBigTextStyleNotification(appNotification);
                    }
                    else
                    {


                    /*if there is url then am running asyncTask to get bitmap of that image and show it in notification tray along with text. Below method does that*/
                        new showBigPictureStyleNotification(MyFirebaseMessagingService.this,
                                appNotification.getMessage(),
                                Links.NOTIFICATION_IMAGE + "/" + appNotification.getPhoto(), appNotification)
                                .execute();

                                /* am passing some variables inside above methods, and Links is a class where have defined some strings (links) to my webapp*/
                    }
                }
            }
        });
        dataFromServer.getAppNotificationFromServer(Long.valueOf(id));




    }

    private void displayNotification(AppNotification appNotification)
    {
        Intent intent = new Intent(MyFirebaseMessagingService.this, NotificationListActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(MyFirebaseMessagingService.this,
                0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle("KSP_PQRS");
        builder.setContentText(appNotification.getSubject());
        builder.setContentIntent(pendingIntent);
        builder.setSmallIcon(R.drawable.notification);
        builder.setSound(notificationSoundUri);
        builder.build();

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(100, builder.build());
    }

    private void showBigTextStyleNotification(AppNotification appNotification)
    {
        Bitmap icon1 = BitmapFactory.decodeResource(getResources(),
                R.drawable.police_logo);

        Android.support.v4.app.NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setAutoCancel(true)
                .setContentTitle(appNotification.getSubject())
                .setSmallIcon(R.drawable.police_logo)
                .setLargeIcon(icon1)
                .setContentText(appNotification.getMessage());

        NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
        bigText.bigText(appNotification.getMessage());
        bigText.setBigContentTitle(appNotification.getSubject());
        bigText.setSummaryText(getResources().getString(R.string.app_name));
        mBuilder.setStyle(bigText);
        mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);

        // Creates an explicit intent for an Activity in your app
        Intent resultIntent;
        if (appNotification.getType().equalsIgnoreCase("GEN"))
        {
            resultIntent = new Intent(this, NotificationListActivity.class);
        }
        else
        {
            resultIntent = new Intent(this, MainActivity.class);
        }

        TaskStackBuilder stackBuilder = TaskStackBuilder
                .create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(((int) appNotification.getId()) + 1000, mBuilder.build());
    }

    private class showBigPictureStyleNotification extends AsyncTask<String, Void, Bitmap>
    {
        private Context mContext;
        private String title, message, imageUrl;
        AppNotification appNotification;

        showBigPictureStyleNotification(Context context, String message, String imageUrl, AppNotification appNotification)
        {
            super();
            this.mContext = context;
            this.title = getResources().getString(R.string.app_name);
            this.message = message;
            this.imageUrl = imageUrl;
            this.appNotification = appNotification;
        }

        @Override
        protected Bitmap doInBackground(String... params)
        {
            InputStream in;
            try
            {
                auth = new AppAuthDAO(mContext).getAppAuth();
                byte[] toEncrypt = (auth.getUsername() + ":" + auth.getPassword() + ":" + auth.getDeviceId()).getBytes();
                String encryptedCredentials = Base64.encodeToString(toEncrypt, Base64.NO_WRAP);

                URL url = new URL(this.imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.setRequestProperty("Authorization", "Basic " + encryptedCredentials);
                connection.connect();
                in = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(in);
                return myBitmap;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return null;
        }

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        protected void onPostExecute(Bitmap result)
        {
            super.onPostExecute(result);

            Intent intent;
            if (appNotification.getType().equalsIgnoreCase("GEN"))
            {
                intent = new Intent(mContext, NotificationListActivity.class);
            }

            else
            {
                intent = new Intent(mContext, MainActivity.class);
            }

            PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_ONE_SHOT);

            NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notif = new Notification.Builder(mContext)
                    .setContentIntent(pendingIntent)
                    .setContentTitle(title)
                    .setContentText(appNotification.getSubject())
                    .setTicker(message)
                    .setSubText(message)
                    .setSmallIcon(R.drawable.police_logo)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.police_logo))

                    /*using setStyle am setting big image along with some lines of text in notifications*/
                    .setStyle(new Notification.BigPictureStyle().bigPicture(result))
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    .build();
            notif.flags |= Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(((int) appNotification.getId()) + 1000, notif);
        }
    }
}
0
Mohammed Farhan