安卓。如何从不同的 Activity 中获取上下文

标签 android android-intent broadcastreceiver google-cloud-messaging

我正在玩 GCM。

使用 https://code.google.com/p/gcm/source/checkout 上的示例一切都很完美 我通过 gcm 消息在我的应用程序上收到通知,

现在我想将消息添加到位于我的 MainActivity 上的 listView 中。

我在另一个类 (GcmIntentService.java) 上接收消息。我怎样才能将 MainActivity 上下文获取到 sendBroadcast。

已经尝试过

private static Context mContext;

public static Context getContext() {
    return mContext;
}

public static void setContext(Context context) {
    mContext = context;
}

但是不工作。

任何想法。

谢谢

最佳答案

我不确定你在做什么。但请记住以下几点

不要保留对上下文 Activity 的长期引用(对 Activity 的引用应与 Activity 本身具有相同的生命周期)。 http://www.curious-creature.org/2008/12/18/avoid-memory-leaks-on-android/

你可以按照下面的方式做

例子:

 new MyClass(ActivityName.this);

class MyClass
{
      Context mContext; 
      public MyClass(Context context)
      {
          mContext=context;
      } 
}

关于安卓。如何从不同的 Activity 中获取上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19334691/

相关文章:

android - 带有@Inject 注释的 ProGuard 和 RoboGuice 的问题

android - Google Play 应用签名流程

android - 在启动 Intent 之前,如何知道系统在android中选择了多少隐式 Intent

android - 为什么 ACTION_MEDIA_BUTTON 无法处理事件?

android - onCheckedChanged

c# - 我如何在基于 Android-Java 的应用程序中使用 DataTable。

android - ACTION_GET_CONTENT : How to get file-ending when searching for multiple file types?

android - 如何在 android 中使用 intent 传递 parcelable 变量值?

Android连接更改广播顺序

java - 开机后多次报警重启