Подтвердить что ты не робот

Spannable string с изображением, не работающим с push-уведомлением

Я пытаюсь использовать spannable строку с изображением на push-уведомлении. Это не работает. На самом деле я хочу показать смайлик в push-уведомлении, например, wattsapp. Если я использую простой spannable string, он работает. То же самое spannable string с изображением отлично работает с textview.

Для этого я также пробовал настраивать push-уведомление, но не добился успеха.

Мой код выглядит следующим образом: -

MainActivity.class

   package com.example.tt.notificationtest;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;

public class MainActivity extends Activity {
    Button btnNotification;
    TextView txtMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtMsg = (TextView) findViewById(R.id.txtMsg);
        btnNotification = (Button) findViewById(R.id.btnNotification);
        btnNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Notify("Testing", "msg");
                Notify2();
            }
        });
    }

    private void Notify2(){
        int icon = R.drawable.asdf;
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, "Custom Notification", when);

        NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
        contentView.setImageViewResource(R.id.image, R.drawable.asdf);

        SpannableString ss = new SpannableString("abcd");
        Drawable d = getResources().getDrawable(R.drawable.asdf);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        contentView.setTextViewText(R.id.title, "Custom notification");
        contentView.setTextViewText(R.id.text, ss);
        notification.contentView = contentView;

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.contentIntent = contentIntent;

        notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification
        notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
        notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
        notification.defaults |= Notification.DEFAULT_SOUND; // Sound

        mNotificationManager.notify(1, notification);
    }

    private void Notify(String notificationTitle, String notificationMessage){

        //This is working

//        SpannableString ss = new SpannableString("Large\n\n" );   // index 103 - 112
//        ss.setSpan(new BackgroundColorSpan(Color.CYAN), 0, 5, 0);



        //this is not working
        SpannableString ss = new SpannableString("abcd");
        Drawable d = getResources().getDrawable(R.drawable.asdf);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        txtMsg.setText(ss);

        Intent i = new Intent(MainActivity.this, MainActivity.class);
        PendingIntent pi=PendingIntent.getActivity(this, 0,
                i,
                0);

        Notification notification = new NotificationCompat.Builder(MainActivity.this)
                .setContentTitle(notificationTitle)
                .setContentText(ss)
                .setSmallIcon(R.drawable.asdf)
//                .setLargeIcon(bitmap)
//                .setDefaults(Notification.DEFAULT_ALL)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(ss))
                .setAutoCancel(true)
                .setContentIntent(pi)
                .build();

        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        nm.notify(2, notification);
    }

}

Activity_main.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="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.tt.notificationtest.MainActivity">

    <TextView
        android:id="@+id/txtMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me"
        android:id="@+id/btnNotification"/>
</LinearLayout>

custom_notification.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="10dp" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/image" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:layout_toRightOf="@id/image" />
</RelativeLayout>
4b9b3361

Ответ 1

Это единственный способ заставить меня работать:

Spanned mssg; mssg = Html.fromHtml(URLDecoder.decode( "% F0% 9F% 98% 82" ));

Он может меняться в зависимости от того, как вы получаете текст, в моем случае я отправляю emojicons, используя unicode, на сервер GCM, и мне не нужно беспокоиться о URLDecoder, но если я получаю сообщение, отправленное с PHP-библиотека emojicon, а не с устройства Android, единственный способ показать его правильно - это с помощью URLDecoder.

Итак, если вы работаете с GCM, он должен работать только с

Spanned mssg; mssg = Html.fromHtml(intent.getStringExtra( "сообщение" ));

Надеюсь, что это поможет!

Ответ 2

В Mixpanel есть рабочее решение для отправки смайликов в push-уведомлениях. Вы можете найти описание здесь

Ответ 3

Вы используете устаревший код здесь

Notification notification = new Notification(icon, "Custom Notification", when);

введите описание изображения здесь

Вместо этого используйте свой RemoteView, например NotificationBuilder.sentContent(remoteView)

Взгляните на Пример пользовательского уведомления