Remoteview отображает системное уведомление, когда приложение не на переднем плане или не работает вместо пользовательского уведомления - PullRequest
2 голосов
/ 09 июля 2019

Прежде всего, позвольте мне рассказать вам, что я сделал до сих пор.Я прошел много поисков, включая

Удаленное представление не применяется в фоновом режиме

firebase_messaging не настраивает уведомление, когда приложение не на переднем плане

Кроме того, я упомянул GitHub и множество статей, но ни одна из них не сработала для меня, поэтому я и задаю этот вопрос, , поэтому, пожалуйста, не отмечайте его как дубликат.

Работает нормально, когда приложение работает, но отображает системное уведомление, когда приложение находится в фоновом режиме.

Нужно ли добавить ссылку custom_notification_layout в манифест? (есть ли meta tag или что-нибудь?)

Это MyFireBaseMessagingService.java класс

public class MyFireBaseMessagingServiceTmp extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        JSONObject jsonObject = new JSONObject(remoteMessage.getData());
        String title = jsonObject.optString("title");
        String message = jsonObject.optString("message");

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel("my_notifications", "My notifications", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }
        RemoteViews remoteViews;
        if (title == "BIG BANG") {
            remoteViews = new RemoteViews(getPackageName(), R.layout.layout_remainder_with_buttons);
        } else {
            remoteViews = new RemoteViews(getPackageName(), R.layout.layout_remainder_no_buttons);
        }
        remoteViews.setTextViewText(R.id.txtTitle, title);
        remoteViews.setTextViewText(R.id.txtMsg, message);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "my_notifications");
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setCustomBigContentView(remoteViews);
        {
            Intent intentGotIt = new Intent("ACTION_GOT_IT");
            PendingIntent pendingIntentGotIt = PendingIntent.getBroadcast(this, 0, intentGotIt, PendingIntent.FLAG_ONE_SHOT);
            remoteViews.setOnClickPendingIntent(R.id.btnGotIt, pendingIntentGotIt);
        }
        {
            Intent intentSnooze = new Intent("ACTION_SNOOZE");
            PendingIntent pendingIntentSnooze = PendingIntent.getBroadcast(this, 0, intentSnooze, PendingIntent.FLAG_ONE_SHOT);
            remoteViews.setOnClickPendingIntent(R.id.btnSnooze, pendingIntentSnooze);
        }
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
        notificationBuilder.setAutoCancel(true);
        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        notificationBuilder.setLargeIcon(icon);
        Notification notification = notificationBuilder.build();
        notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        notification.vibrate = new long[]{0, 400, 200, 400};
        notificationManager.notify(1000, notification);
    }
}

Это layout_remainder_with_buttons.xml макет

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:background="@drawable/bg_gradient_blue">

        <ImageView
            android:id="@+id/ivLogo"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_centerVertical="true"
            android:layout_marginStart="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginEnd="5dp"
            android:layout_marginBottom="10dp"
            android:src="@drawable/logo_round" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toEndOf="@+id/ivLogo"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:padding="5dp">

        <TextView
            android:id="@+id/txtTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/white"
            android:textSize="16sp"
            android:textStyle="bold"
            tools:text="Notification title" />

        <TextView
            android:id="@+id/txtMsg"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txtTitle"
            android:textColor="@color/white"
            android:textSize="14sp"
            tools:text="Notification msg" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            tools:visibility="visible">

            <Button
                android:id="@+id/btnGotIt"
                android:layout_width="100dp"
                android:layout_height="30dp"
                android:layout_marginEnd="10dp"
                android:background="@drawable/bg_button_oval_green"
                android:gravity="center"
                android:padding="5dp"
                android:text="Got it...!"
                android:textAllCaps="true"
                android:textColor="@color/white"
                android:textStyle="bold" />

            <Button
                android:id="@+id/btnSnooze"
                android:layout_width="100dp"
                android:layout_height="30dp"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:background="@drawable/bg_button_oval_red"
                android:gravity="center"
                android:padding="5dp"
                android:text="Snooze"
                android:textAllCaps="true"
                android:textColor="@color/white"
                android:textStyle="bold" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

Это layout_remainder_no_buttons.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:background="@drawable/bg_gradient_blue">

    <ImageView
        android:id="@+id/ivLogo"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerVertical="true"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="5dp"
        android:src="@drawable/logo_round" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toEndOf="@+id/ivLogo"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:padding="5dp">

        <TextView
            android:id="@+id/txtTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Remainder"
            android:textColor="@color/white"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/txtMsg"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txtTitle"
            android:ellipsize="end"
            android:maxLines="2"
            android:text="Its time to place order for `For Father`"
            android:textColor="@color/white"
            android:textSize="14sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txtMsg"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="horizontal"
            android:visibility="gone">

            <Button
                android:id="@+id/btnSave"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:layout_weight="1"
                android:background="@null"
                android:gravity="center"
                android:padding="5dp"
                android:text="Got it...!"
                android:textAllCaps="true"
                android:textColor="@color/white"
                android:textStyle="bold" />

            <Button
                android:id="@+id/btnCancel"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:layout_weight="1"
                android:background="@null"
                android:gravity="center"
                android:padding="5dp"
                android:text="Snooze"
                android:textAllCaps="true"
                android:textColor="@color/app_red"
                android:textStyle="bold" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

1 Ответ

1 голос
/ 09 июля 2019

со стороны сервера

Убедитесь, что "Вы NOT отправляете " notification " в поле " notification payload ", а если вы отправляете? , то , пожалуйста, удалите поле notification из запроса к вашему серверу и отправьте только данные .

, потому что когда вашприложение находится в фоновом режиме, чем Android NOT выполнит onMessageReceived, и система примет это уведомление и покажет "Нормальное уведомление".

Итак, отправьте только "data" в вашПолезная нагрузка уведомления. Также добавьте {"priority": "high"} в полезную нагрузку уведомления.

Вот пример ответа сервера

{
  "to": "your_fcm_token",
  "priority": "high",
  "data":{
    "title": "Your title",
    "msg": "your msg",
    "other_info": "etc"
  }
}

Надеюсь, это поможет:)

...