将字符串从 Activity 调用到另一个

Call String from Activity to another

我想将一个字符串从 Activity 调用到另一个。这不像普通调用那样简单,但是当我打开通知时会发生此调用。 我有一个存储字符串的通知打开处理程序。我想调用存储在字符串 titlebody 中的值 这是打开处理程序的代码。

 public class MyNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
private Context mContext;
public MyNotificationOpenedHandler (Context context) {
   mContext = context;
}
@Override
public void notificationOpened(OSNotificationOpenResult result) {
    OSNotificationAction.ActionType actionType = result.action.type;
    JSONObject data = result.notification.payload.additionalData;
    String title = result.notification.payload.title;
    String body = result.notification.payload.body;
    String launchUrl = result.notification.payload.launchURL; // update docs launchUrl

    String customKey;
    String openURL = null;
    Object activityToLaunch = AboutActivity.class;

    if (data != null) {
        customKey = data.optString("customkey", null);
        openURL = data.optString("openURL", null);

        if (customKey != null)
            Log.i("OneSignalExample", "customkey set with value: " + customKey);

        if (openURL != null)
            Log.i("OneSignalExample", "openURL to webview with URL value: " + openURL);
    }


    Intent intent = new Intent(mContext, (Class<?>) activityToLaunch);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("openURL", openURL);
    Log.i("OneSignalExample", "openURL = " + openURL);
    mContext.startActivity(intent);

}
}

主要问题如何在其他活动中调用字符串 titlebody

立即使用捆绑包或额外添加:

Intent intent = new Intent(mContext, (Class<?>) activityToLaunch);
intent.putExtra("title", title);
intent.putExtra("body", body);
mContext.startActivity(intent);

在下activity:

Intent intent = getIntent();
String title = intent.getStringExtra("title");
String body = intent.getStringExtra("body");

如果结构比较复杂,可以使用bundle。

Bundle bundle = new Bundle();
bundle.putString("title", title);
bundle.putString("body", body);
intent.putExtras(bundle);

如果数据需要成为整个应用程序的全局变量, 您可以扩展 Application 并为这些数据实施 getter 和 setter。

此外,您可以将标题和 body 放入数据库或 SharedPreferences,然后从任何您想要的 activity 读取它。请确保不要在 UI 线程中执行 i/o 任务。