【发布时间】:2011-03-02 23:10:54
【问题描述】:
我有一个主要活动,它启动一项服务以在后台进行网络搜索,我希望主要活动在搜索完成后获得一个意图。
在我的主要活动中,我定义了一个 BroadcastReceiver 和一个 Intent Filter 来监听“搜索结束”的意图:
public class AgeRage extends Activity {
// Listener to all results from background processes
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ImageSearchService.SEARCH_RESULT_ACTION)) {
0);
Toast.makeText(context,"Got " + i + "results", Toast.LENGTH_SHORT).show();
}
else Toast.makeText(context,"unknown intent", Toast.LENGTH_SHORT).show();
}
};
IntentFilter receiverFilter = new IntentFilter ();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Register to image search service messages
receiverFilter.addAction(ImageSearchService.SEARCH_RESULT_ACTION);
registerReceiver(receiver,receiverFilter);
...
在服务中,我进行搜索,完成后,我发送一个 Intent:
public class ImageSearchService extends IntentService {
...
protected void onHandleIntent (Intent intent) {
... doing search ...
Intent i = new Intent (this,AgeRage.class);
i.setAction (SEARCH_RESULT_ACTION);
i.putExtra(SEARCH_STATUS, (searchStatus ==SearchStatus.DONE) ? true:false);
i.putExtra (SEARCH_RESULT_NUM, totalResultNum);
i.putExtra (SEARCH_ID, searchID);
sendBroadcast (i,null);
}
但是,主要活动没有获得意图。我知道正在调用 sendBroadcast 而不是接收者的 OnReceive(使用调试器检查)。
我假设由于我是动态创建过滤器的,我不需要在清单文件中定义过滤器。
我做错了吗?
谢谢 艾萨克
【问题讨论】:
-
不确定您的问题您实际上使服务交互比它需要的更复杂。由于该服务是本地服务,因此您可以直接与它对话并让它在完成时通知您的活动,而无需广播 Intent 并使用 Receiver 进行侦听。查看stackoverflow.com/questions/3197335/android-restful-api-service/…
-
谢谢,我刚刚更改了我的代码以与接收器一起使用,它运行良好。
-
在stackoverflow.com/questions/4233873/…这个话题很好的讨论
标签: android android-intent broadcastreceiver intentfilter