3

發送廣播的服務與接受它在我項目,當Service開始,我發送一個廣播:在AndroidTestCase

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 ===========

之後我刪除了這條線:發送廣播時AndroidTestCaseintent.setPackage("com.my.project.test"),我的接收機接收現在播放。

但現在,我想知道爲什麼明確設置包的意圖阻止接收機測試項目,即使我設置的包名字是我的測試項目。在我的測試項目的AndroidManifest.xml中,我有我的包的名稱定義:

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

'AndroidTestCase'是一個'Service','Activity'還是什麼? – Kristopher

+0

這是Android測試框架中的一般測試用例類:http://developer.android.com/reference/android/test/AndroidTestCase.html。我提到的服務在我的項目中沒有測試項目。 – Mellon

回答

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 answer.Hope看看它會幫助ü !

+0

其實,它並不是因爲代碼中的順序,我有intent.setPackage(「com.my.project.test」),我刪除了這一行後,它工作正常,我的接收器在AndroidTestCase類正在接收廣播現在。但現在,我想知道爲什麼明確地設置意圖封裝阻止接收器... – Mellon

相關問題