android - 有没有办法在不使用 Intent 的情况下在 Activity 之间发送数据?

标签 android

我有一个每个用户唯一的用户名,我想发送给某个 Activity ,但我不想使用 Intent :

    //create an intent and sends username
     Intent intent = new Intent(RegisterOwner.this, Owner.class);
     intent.putExtra("USERNAME",usernam);
     startActivity(intent);

我想向 Activity 发送数据而不去那个 Activity ,startActivity(intent); 让我去 Activity ;我不想这样。

我只想发送数据而不启动其他 Activity 。

最佳答案

我想您希望在 Activity 之间提供特定的数据。实现此目的的方法之一是使用 SharedPreferences。

来自您的第一个 Activity (RegisterOwner)

SharedPreferences mySharedPreferences = this.getSharedPreferences("MYPREFERENCENAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("USERNAME",usernam);
editor.apply();

执行此操作后,用户名将存储在共享首选项中。现在您可以在整个应用程序中使用这些数据。

因此,您可以从 Owner Activity 中按如下方式检索:

SharedPreferences mySharedPreferences = this.getSharedPreferences("MYPREFERENCENAME", Context.MODE_PRIVATE);
String username = mySharedPreferences.getString("USERNAME", "");

关于android - 有没有办法在不使用 Intent 的情况下在 Activity 之间发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51794094/

相关文章:

android - 无法检测设备兼容性。请选择目标设备

android - 我怎样才能捕获我的 EditText 文本的格式,以便下次我在 TextView 中显示粗体字时将它们显示为粗体

android - java.lang.String类型的Value <br无法转换为JSONObject如何解决?

android - 如何在 android 中使用 Social Auth 获取 twitter 的好友列表?

android - 在 Android 中发送和接收短信和彩信(Kit Kat Android 4.4 之前)

java - Android 中的仪表

java - 出现错误 "Unfortunately you ### application has stopped"

java - 通过改造上传文件

android - Retrofit Request Interceptor 阻塞主线程

java - android gomobile 上的 "Unsupported flags DT_FLAGS_1=0x9"错误