学习小记--android静态注册广播接收器之惑--6.6

来源:互联网 发布:fangcms源码下载 编辑:程序博客网 时间:2024/05/22 12:57

今天工作中遇到一个问题,当静态注册(XML注册)broadcastreceiver时,发送自定义的广播未收到。下面是我的例子程序

发送广播的地方,是一个单独应用A。

package com.test.sendbroadcast;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;public class TestSendBroadcastActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View v) {                // TODO Auto-generated method stub                Intent intent = new Intent();                intent.setAction("com.test.receiver.action");                Log.i("TAG", "sendBroadcast  action = com.test.receiver.action");                TestSendBroadcastActivity.this.sendBroadcast(intent);            }        });    }}

接收广播地方,也是单独应用B,其中只有这个一个接收器,无其它Activity

package com.test.receiver;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class TestReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        // TODO Auto-generated method stub        Log.i("TAG", "onReceive --> action = " + intent.getAction());    }}

XML注册如下

        <receiver android:name="TestReceiver">            <intent-filter>                <action android:name="android.intent.action.SCREEN_OFF"/>                <action android:name="android.intent.action.SCREEN_ON"/>                <action android:name="com.test.receiver.action"/>            </intent-filter>        </receiver>

测试结果,在android4.0.3上未接收到任务广播。
 

在android2.2上接收到,自定义的广播,未收到熄屏与亮屏广播。

最终用模拟器一一实验,得到在3.0能收到,3.1就收不到了。

当我在BroadcastReceiver的应用中加入一个action=MAIN,category=LAUNCHER的Activity时,发现自定义的广播都可以收到了,但SCREEN_ON与SCREEN_OFF消息还是收不到。

这到底是为什么呢?

http://stackoverflow.com/questions/2575242/android-intent-action-screen-on-doesnt-work-as-a-receiver-intent-filter这里有说到上面的SCREEN_ON SCREEN_OFF不起作用。

http://blog.csdn.net/r8hzgemq/article/details/7995970这里有说到自定义在3.1后表现不同的原因是android sdk出于安全考虑,防止一些软件在用户不知情的情况下就自动启动起来了,所以做了些限制。

查看了http://www.blogjava.net/mixer-a/archive/2012/04/17/374979.html分析的广播流程,对比了GB与ICS代码,ICS在ActivityManagerService中的broadcastIntentLocked方法加上了如下代码,算是解释了上面的说法。

        // By default broadcasts do not go to stopped apps.        intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);