前几天写了个短信提醒的程序,接受系统广播,然后弹Toast提示。但是实验了几次都不成功,反复检查发现没有错误,只好放下。今天写个开机自启动服务,发现也无法接收系统广播。在自己机器上试了一下竟然可以,以为是虚拟机的问题,在网上找了找没有任何头绪。这时候突然想到自己机器是2.3的,虚拟机是4.0版本的,会不会是这里出了问题。
上网一搜果然这版本的问题,3.1开始的android加入了一种保护机制,正是这个机制导致程序接收不到系统广播。官方说明如下:
Launch controls on stopped
applications
Starting from Android 3.1, the system's package
manager keeps track of applications that are in a stopped state and
provides a means of controlling their launch from background
processes and other applications.
Note that an application's stopped state is not the same as an
Activity's stopped state. The system manages those two stopped
states separately.
The platform defines two new intent flags that let a sender
specify whether the Intent should be allowed to activate components
in stopped application.
—
Include intent filters of stopped applications in the list of
potential targets to resolve against.
—
Exclude intent filters of stopped applications from the list of
potential targets.
When neither or both of these flags is defined in an intent, the
default behavior is to include filters of stopped applications in
the list of potential targets.
Note that the system adds to
all broadcast intents. It does this to prevent broadcasts from
background services from inadvertently or unnecessarily launching
components of stoppped applications. A background service or
application can override this behavior by adding theflag
to broadcast intents that should be allowed to activate stopped
applications.
Applications are in a stopped state when they are first
installed but are not yet launched and when they are manually
stopped by the user (in Manage Applications).
简单的说就是系统广播都添加了一个flag(FLAG_EXCLUDE_STOPPED_PACKAGES),这样的结果就是一个处于"stopped"状态(安装后未启动过或者被用户在管理应用中手动停止)的就不能接收系统的广播。这样就可以防止病毒木马之类的恶意程序。但是自己定义的广播可以通过添加另一个flag,使可以启动处于"stopped"状态的程序,但是系统广播就无能为力了。网友们说经过验证,系统级别的app不受这个限制的影响。
这样的话,如果只有一个服务程序,就无法接收系统广播,因为服务程序无法手动启动,会一直处于"stopped"状态。暂时还没看到啥解决方法。。。。