将数据从广播传递到活动(Pushy.me)

时间:2019-09-24 20:33:42

标签: android broadcastreceiver pushy

我正在尝试使用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());
}

}

1 个答案:

答案 0 :(得分: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);