为什么我的广播接收器调用其他方法? [英] Why won't my BroadcastReceiver call other methods?

查看:131
本文介绍了为什么我的广播接收器调用其他方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个BroadcastReceiver,可以成功地搭上了广播,但如果我尝试调用它从另一种方法,它不会总是工作。这里是我的设置:

I have a BroadcastReceiver that can successfully catch a broadcast, but if I try to call another method from it, it won't always work. Here's my setup:

private class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (working == true) {
            //toast to make sure we got here
            doWork();
        }
    }
}

之内,如果被调用,但的doWork不执行敬酒。有没有人处理类似的问题?

The toast within the if gets called, but doWork doesn't execute. Has anyone dealt with a similar issue?

推荐答案

广播接收器不具有相同的背景和生命周期为您的应用程序,你不能做很多正常的东西在里面。所有应该做的是处理该事件,并返回尽可能快。换句话说,启动一个服务,或通知用户。

The Broadcast receiver doesn't have the same context and life cycle as your application, you can't do a lot of normal stuff in it. All your supposed to do is handle the event and return as quick as possible. In other words, start a service, or notify the user.

来源: http://developer.android.com/reference/android/内容/ BroadcastReceiver.html

一个BroadcastReceiver对象仅适用于调用的onReceive(上下文,意图)的持续时间。一旦这个函数的code返回时,系统会认为这个对象被完成并不再有效。

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

这有您可以在的onReceive做什么重要的影响(上下文,意图)执行:任何需要异步操作不可用,因为你需要从处理异步操作函数返回,但在这一点上该广播接收器不再有效,因此该系统是免费的异步操作完成之前杀死它的进程。

This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.

在特别的,你可能无法从一个BroadcastReceiver中显示一个对话框或绑定到服务。对于前者,你应该改用NotificationManager API。对于后者,你可以使用Context.startService()将命令发送到服务。

In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service.

这篇关于为什么我的广播接收器调用其他方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆