发送广播服务&在AndroidTestCase中收到它

时间:2013-10-18 08:21:57

标签: android performance android-intent broadcastreceiver android-broadcast

在我的项目中,当Service开始时,我发送广播:

Intent intent = new Intent("my.service.action");
intent.setPackage("com.my.project.test"); //only broadcast to my test project
getApplicationContext().sendBroadcast(intent);
Log.i("tag","broadcast is sent!");

在我的测试项目 AndroidTestCase中,我开始&绑定Service,这也会触发广播发送。所以,我决定也在AndroidTestCase

收到这个广播
public class MyTestCase extends AndroidTestCase{ 
  ...
  @Override
  public void setUp() throws Exception{
    super.setUp();
     //This is working fine, I can see the broadcast is sent log in service
     bindToService() 

     //register broadcast receiver 
     IntentFilter filter = new IntentFilter("my.service.action");
     getContext().registerReceiver(mMyReceiver, filter);
  }

  public BroadcastReceiver mMyReceiver = new BroadcastReceiver(){

      @Override
      public void onReceive(Context context, Intent intent) {
      //BUT the broadcast sent in service is not received in my test case, why?
      Log.i(TAG, "Received in test case!");

     }  
 };
}

如您所见,我已在我的AndroidTestCase测试项目中注册了广播接收器。虽然广播是在我项目的Service中发送的,但是没有收到。为什么呢?

========== UPDATE ===========

在我发送广播后删除此行:intent.setPackage("com.my.project.test")后,我AndroidTestCase课程的接收器正在接收广播。

但是现在,我想知道为什么在测试项目中明确设置意图阻止接收器的包,即使我设置的包名是我的测试项目。在我的测试项目的 AndroidManifest.xml 中,我有我的包名称定义:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.my.project.test"
   ...

1 个答案:

答案 0 :(得分:1)

@Override
  public void setUp() throws Exception{
    super.setUp();
     //This is working fine, I can see the broadcast is sent log in service
     bindToService() 

     //register broadcast receiver 
     IntentFilter filter = new IntentFilter("my.service.action");
     getContext().registerReceiver(mMyReceiver, filter);
  }

更改为:

@Override
  public void setUp() throws Exception{
    super.setUp();

     //register broadcast receiver 
     IntentFilter filter = new IntentFilter("my.service.action");
     getContext().registerReceiver(mMyReceiver, filter);

   //This is working fine, I can see the broadcast is sent log in service
     bindToService();

  }

看看this回答。希望它能帮助你!!