【问题标题】:How to send data from a class to an Activity in Android如何将数据从类发送到 Android 中的 Activity
【发布时间】:2016-12-28 02:06:17
【问题描述】:

我正在为推送通知实施 FCM(Firebase 云消息传递)。我可以成功地使用我的服务类从服务器获得推送通知。但是,如何将数据(消息)从服务类发送到活动?

Service.java

public class Service extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        sendNotification(remoteMessage.getNotification().getBody());
    }


    private void sendNotification(String messageBody) {

        Intent intent = new Intent(this, FCMActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri =RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new
                NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase Push Notification")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
        notificationBuilder.setLights(Color.RED, 1000, 300);
        NotificationManager notificationManager =
                (NotificationManager)
                        getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }
}

FCMActivity.java

public class FCMActivity extends AppCompatActivity {
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fcm);

        mTextView = (TextView) findViewById(R.id.txt);
    }
}

【问题讨论】:

  • 想将“messageBody”发送到我的活动中。

标签: java android android-studio android-activity


【解决方案1】:

有几个选项,其中包括:

  1. 在您的 Activity 中注册一个 BroadcastReceiver 并使用 IntentFilter 为您的自定义操作(操作只是广播消息类型的 String 标识符),并使用 LocalBroadcastManager.getInstance().sendBroadcast(Intent intent) 方法从服务发送广播

  2. 使用事件总线,例如非常流行的GreenRobot EventBus 库。解释见https://github.com/greenrobot/EventBus#eventbus-in-3-steps

这两个选项都需要在您的 Activity 中注册和取消注册侦听器/接收器,对于应该触发 UI 更改的事件,最好在 onResume/onPause 中完成。

另外,您可以bind to the service from your Activity

【讨论】:

  • 如果你决定使用 BroadcastReceiver,最好的选择是在 onResume() / onPause() 中注册/取消注册,否则会抛出“IllegalStateException: Can not perform this action after onSaveInstanceState” .这也将减少不必要的系统开销。
【解决方案2】:

您应该在服务中使用IBinder,在活动中使用ServiceConnection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2013-09-27
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多