【问题标题】:Send intent from GcmIntentService to the current activity without starting the activity从 GcmIntentService 向当前活动发送意图而不启动活动
【发布时间】:2014-08-13 02:30:53
【问题描述】:

如何从GcmItentService 向当前打开的 Activity 发送 Intent。在更新活动中的列表之前,我需要来自推送通知的数据。我不想要的是调用 startActivity(Intent) (因为显然活动已经打开)。此外,当活动仍处于打开状态时,不会调用 onResume 方法。假设我有一个要发送到当前活动的字符串,我该怎么做才能实现呢?

我已经完成了该线程中所述的内容: Intent Extras of GCMIntentService is not passed ,但我无法让它工作。非常感谢一个简单的分步说明。

【问题讨论】:

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


    【解决方案1】:

    您可以简单地使用 LocalBroadcastManager。

    帮助注册并向本地对象发送 Intent 广播 在你的过程中。与发送相比,这具有许多优点 使用 sendBroadcast(Intent) 进行全球广播:

    • 您知道您正在广播的数据不会离开您的应用程序,所以 无需担心泄露私人数据。
    • 这是不可能的 其他应用程序将这些广播发送到您的应用程序,因此您不需要 需要担心有他们可以利用的安全漏洞。
    • 更多的是 比通过系统发送全球广播更有效。
    Intent intent = new Intent(YOUR_ACTION_NAME);
    intent.putExtra("PushType", "test");            
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    

    在您的活动中编写一个接收器来处理“YOUR_ACTION_NAME”操作

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        LocalBroadcastManager.getInstance(this).registerReceiver(
                messageReceiver, new IntentFilter("YOUR_ACTION_NAME"));
    }
    
    
    private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
    
        }
    };
    

    更多详情:LocalBroadcastManager

    【讨论】:

    • 看起来不错。我明天会试试这个并接受你的回答:)
    • 谢谢。正是我想要的。
    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    相关资源
    最近更新 更多