【问题标题】:Call an activity method from a BroadcastReceiver. Is it possible?从 BroadcastReceiver 调用活动方法。可能吗?
【发布时间】:2011-07-03 12:26:46
【问题描述】:

我一直在开发应用程序,因为我需要在触发 BroadcastReceiver 时调用我的活动方法。我希望 BroadcastReceiver 检测网络连接何时断开并调用我已经编写的活动方法。

我一直在搜索,我发现以前有更多人问过这个问题,但没有人得到关于如何做到这一点的答案。

我认为也许 android 的 API 不允许这样做。如果无法从 BroadcastReceiver 调用我的活动方法,还有其他方法吗?

谢谢。

【问题讨论】:

  • Activity上的方法是做什么的?
  • 它检查进程变量(属于 Activity)是否未设置为 null(进程已启动),并在根 shell 中执行一个命令来杀死该进程。

标签: android methods android-activity broadcastreceiver


【解决方案1】:

试试这样的..

在你的活动代码中写

BroadcastReceiver connectionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            myActivityMethod();// Here you call method
        }
    };

    registerReceiver(connectionReceiver, new IntentFilter("com.test.NET_CONNECTION"));

在你的服务中写

Intent intent = new Intent("com.test.NET_CONNECTION");
        sendBroadcast(intent);

如果有任何困惑,请告诉我,我会尽力解决..

【讨论】:

  • 尽管我不使用服务(仅一个活动),但我使用了活动中的代码并省略了服务的代码。它工作得很好。非常感谢您的帮助!这个问题让我发疯了好几天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
相关资源
最近更新 更多