2

在我的项目中,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我的项目中发送的,但没有收到。为什么?

==========更新===========

在我删除这一行之后:intent.setPackage("com.my.project.test")发送广播时,我在AndroidTestCase课堂上的接收器现在正在接收广播。

但是现在,我想知道为什么显式设置 package for intent 会阻塞测试项目中的接收器,即使我设置的包名是我的测试项目。在我的测试项目的AndroidManifest.xml中,我有我的包名定义:

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

1 回答 1

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();

  }

看看这个answer.Hope它会帮助你!

于 2013-10-18T08:41:10.957 回答