【问题标题】:Android: Passing a variable to a non-activity classAndroid:将变量传递给非活动类
【发布时间】:2015-10-16 11:35:09
【问题描述】:

我正在尝试将我的 MainActivity 中的字符串传递给非活动类(通知服务),以便我可以自定义通知消息。我尝试过使用 Intent 但它不起作用,因为它是一个非基于活动的类。这样做的最佳理由是什么?

我目前正在尝试使用全局变量,但它不起作用。

MainActivity.java

private String var;
private String a = "Pumpkin";

public String getVar(){
    return var;
}
public void setVar(String a){
    var = a;
}

NotificationService.java

  MainActivity b = ((MainActivity)getApplicationContext());
  String var = b.getVar();

即使我在 NotificationService.java 中调用变量 var 也会导致应用程序崩溃

【问题讨论】:

  • 它崩溃是因为应用程序上下文不是您的活动。

标签: java android parameter-passing android-notifications


【解决方案1】:

1.您可以尝试制作静态变量,并在任何地方使用类引用进行调用。

 public static  String a = "Pumpkin";//Declare in MainActivity
 Use it: String var = MainActivity.a;

2。将 Intent 作为 extras 传递,然后在收到 intent 的地方获取 extras。

  startActivity(new Intent(MainActivity.this, PropertyListviewActivity.class).putExtra("Key", "Value"));

接收:

 if (intent != null)
        if (intent.getExtras() != null)
            if (intent.getExtras().getString("Key") != null) {
                String recivedString= intent.getExtras().getString("Key");

3.保持共享偏好并在任何你想要的地方检索(不好的做法)。

4.If Not an Android Component class try pass in Contractor。

【讨论】:

  • 我强烈建议使用第二个选项。第一个和第三个本质上都是全局变量,它们使应用程序更难维护。 Intent 的附加功能是最接近方法参数的东西。如果您确定要传递参数,则不需要所有这些 null 检查。
【解决方案2】:

尝试使用事件总线 Green RobotOtto Event Bus 都是不错的选择。

【讨论】:

  • 我会说这是一种相当先进的方法。您应该首先学会通过意图和信使进行交流,然后转向像 Otto 这样的神奇解决方案。
  • 你是对的,但我写出了最简单的解决方案:)。
【解决方案3】:

您正在尝试将应用上下文转换为 Activity。它崩溃了,因为应用上下文不是一个活动。您应该在服务中使用 handleIntent 或 binder 来传输数据。 http://developer.android.com/guide/components/bound-services.html#Basics

【讨论】:

【解决方案4】:

您可以通过将数据保存到应用程序级变量或将其保存在 sharedpreference 中来完成此任务。

在应用程序级别保存数据 制作一个静态变量,如

public static DatatypeYouDesire(String/int) cachedData;

现在,当您要存储数据时,只需使用您要存储的数据初始化此变量 喜欢

YourApplictionClass.cachedData = "your data to be stored";

同样,您可以通过访问 YourApplicationClass.cacheData 来使用这些数据

【讨论】:

  • 虽然有时避免它需要额外的工作,但全局应用程序状态很糟糕。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多