gpt4 book ai didi

android - 在 Service 中发送广播并在 AndroidTestCase 中接收

转载 作者:行者123 更新时间:2023-11-29 01:49:02 28 4
gpt4 key购买 nike

在我的项目中,当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 中,我启动并绑定(bind)了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 类中的接收器正在接收广播现在。

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

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

最佳答案

@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回答。希望对你有帮助!!

关于android - 在 Service 中发送广播并在 AndroidTestCase 中接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19444871/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com