0

我正在尝试使用 Pushy.me。我可以获取和解析数据,但我想用这些数据更新 UI。如何将数据从 BroadcastReceiver 传递到 Activity?

我的接收器类:

public class PushReceiver extends BroadcastReceiver {

private LocalBroadcastManager broadcaster;
public static String REQUEST_ACCEPT = "REQUEST_ACCEPT";

@Override
public void onReceive(Context context, Intent intent) {
    String notificationTitle = "Title";
    String notificationText = "Text";

    /**/

    Bundle bundle = intent.getExtras();
    JSONObject jsonObject = new JSONObject();

    for (String key : bundle.keySet()) {
        Object obj = bundle.get(key);
        try {
            jsonObject.put(key, wrap(bundle.get(key)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String message = jsonObject.get("body").toString();

    // Prepare a notification with vibration, sound and lights
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setAutoCancel(true)
    ...
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));

    // Automatically configure a Notification Channel for devices running Android O+
    Pushy.setNotificationChannel(builder, context);

    // Get an instance of the NotificationManager service
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

    // Build the notification and display it
    notificationManager.notify(1, builder.build());
}

}

4

1 回答 1

1

您可以在活动中创建本地广播接收器

BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent.getAction() == "my_action"){
                    intent.getStringExtra("data");
                }
            }
        };

        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, new IntentFilter("my_action"));

在 PushReceiver 类中

Intent intent = new Intent("my_action");
intent.putExtra("data", message);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
于 2019-09-24T21:59:49.533 回答