java - 通过 Firebase 单击通知获取 Intent Extra

标签 java android firebase android-intent firebase-cloud-messaging

通知中心会出现带有图像的通知(即使应用程序已关闭|应用程序位于后台),每当我单击通知时, Activity 都会将其打开,但没有 Intent 数据。

每当我试图获得额外的 Intent 时,我总是得到 null。无论我努力通过Bundle传递数据还是直接传入intent.setExtra,我总是得到null。

<小时/>

我有一个 Firebase 处理程序类

public class MyFirebaseInstanceService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //super.onMessageReceived(remoteMessage);
        String msg = remoteMessage.getNotification().getBody();
        String title = remoteMessage.getNotification().getTitle();
        String channel = remoteMessage.getNotification().getChannelId();
        Holder holder = new Holder();
        holder.setTitle(title);
        holder.setMsg(msg);
        holder.setChannel(channel);
        if (remoteMessage.getData().size() > 0) {
            Map<String, String> params = remoteMessage.getData();
            holder.setId(params.get("id"));
            holder.setImgUrl(params.get("imgurl"));
            holder.setType(params.get("type"));
        } else {
            int r = new Random().nextInt();
            holder.setId(r + "");
            holder.setType("bigtext");
        }
        sendMyNotification(holder, remoteMessage);
    }

    private void sendMyNotification(Holder holder, RemoteMessage remoteMessage) {
        String clickAction = remoteMessage.getNotification().getClickAction();
        Intent intent = new Intent(this, NotificationReadActivity.class);
        if (clickAction != null) {
            if (!clickAction.isEmpty() && clickAction.length() > 5)
                intent = new Intent(clickAction);
        }
        intent.putExtra("obj", holder);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setAction(holder.getId() + "");
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, holder.getChannel());
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        notificationBuilder.setChannelId(holder.getChannel());
        if (holder.getType().equals("bigpic")) {
            notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle());
            Bitmap bitmap = getBitmapfromUrl(holder.getImgUrl());
            if (bitmap != null) {
                notificationBuilder.setLargeIcon(bitmap);
            }
        } else {
            notificationBuilder.setStyle(new NotificationCompat.BigTextStyle());
        }
        notificationBuilder.setContentTitle(holder.getTitle());
        notificationBuilder.setContentText(holder.getMsg());
        PendingIntent pendingIntent = PendingIntent.getActivity(this, holder.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
        notificationBuilder.setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(holder.getChannel(), "Default", NotificationManager.IMPORTANCE_DEFAULT);
                channel.enableLights(true);
                channel.enableVibration(true);
                channel.setLightColor(Color.RED);
                channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                notificationManager.createNotificationChannel(channel);
            }
            notificationManager.notify(holder.getId(), notificationBuilder.build());
        } catch (Exception ignored) {
        }
    }

    private Bitmap getBitmapfromUrl(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            return BitmapFactory.decodeStream(input);
        } catch (Exception ignored) {
            return null;
        }
    }
}

然后我有一个 Activity

public class NotificationReadActivity extends AppCompatActivity {

    TextView title, desc;
    AppCompatImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification_read);
        title = findViewById(R.id.title);
        desc = findViewById(R.id.desc);
        img = findViewById(R.id.img);
        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        Bundle bundle = intent.getExtras();
        if (intent.hasExtra("obj")) {
            Holder holder = (Holder) intent.getSerializableExtra("obj");
            if (holder.getType().equals("bigpic")) {
                Glide.with(this).load(holder.getImgUrl()).into(img);
            } else
                img.setVisibility(View.GONE);
            title.setText(holder.getTitle());
            desc.setText(holder.getMsg());
        } else if (bundle.containsKey("obj")) {
            Holder holder = (Holder) bundle.getSerializable("obj");
            if (holder.getType().equals("bigpic")) {
                Glide.with(this).load(holder.getImgUrl()).into(img);
            } else
                img.setVisibility(View.GONE);
            title.setText(holder.getTitle());
            desc.setText(holder.getMsg());
        } else {
            title.setText("Null");
            //finish();
        }
    }
}

在 list 中我也设置正确

<activity
   android:name=".NotificationReadActivity"
   android:excludeFromRecents="true"
   android:label="@string/notification_center"
   android:launchMode="singleTop">
      <intent-filter>
         <action android:name="com.full_package.NotificationReadActivity.TARGET_NOTIFICATION" />

         <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
</activity>
<service
   android:name=".Fcm.MyFirebaseInstanceService"
   android:exported="true"
   android:permission="com.google.android.c2dm.permission.SEND">
      <intent-filter>
         <action android:name="com.google.firebase.MESSAGING_EVENT" />
         <action android:name="com.google.android.c2dm.intent.RECEIVE" />
      </intent-filter>
</service>

最佳答案

我想出了唯一的解决方案是传递字符串或整数或除 Intent 中的对象之外的任何类型的数据都可以。 Intent.putExtra 无法处理或传递对象。

Intent intent = new Intent(this, NotificationReadActivity.class);
intent.putExtra("key1", "some string"); //this is correct
intent.putExtra("key2", 123); //this is correct
intent.putExtra("key3", any type of data); //this is correct

intent.putExtra("object", some_object); //this is in-correct

关于java - 通过 Firebase 单击通知获取 Intent Extra,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60915273/

相关文章:

java - 在 Spring 中与 PathVariable 一起使用时 CSS 未加载

java - 使用流收集列表中最大的连续序列整数

javascript - 如何从 Firebase timeStamp 获取当前数据

java - 通过 J2EE 应用程序压缩运行应用程序服务器的远程计算机中的文件夹

java - 设计模式,它们与其他编程风格有何不同?

android - 了解 GetView 方法的 convertView 参数

android - Phonegap 默认主题不显示带有箭头符号的 ListView

android - 如何在 React Native 中获取本地视频列表并以网格格式显示?

node.js - Firebase Admin SDK 用于从服务器登录用户

Swift 4 Firebase 在 TableView 上显示用户组