Android BroadcastReceiver,ContentProvider和Activity之间的数据流? [英] Dataflow between Android BroadcastReceiver, ContentProvider, and Activity?
问题描述
我已经开发了一个接收广播的应用程序,然后
启动Activity
,其中Activity
查询ContentProvider
实时从DNS中提取信息.
I've developed an application that receives a Broadcast and then
launches an Activity
, where that Activity
queries a ContentProvider
which pulls information out of the DNS in real-time.
我希望能够对此进行洗牌,而不是去做:
I'd like to be able to shuffle this so that instead of going:
BroadcastReceiver.onReceive() {
Intent intent = new Intent(...);
intent.setData(...); // set a single String data
context.startActivity(intent);
}
Activity.onCreate() {
String value = intent.getData(); // get the String data
Cursor = ContentProvider.query(search);
...
setContentView(...);
}
进展:
BroadcastReceiver.onReceive() {
Cursor = ContentProvider.query(...);
if (cursor != null) {
Intent intent = new Intent(...);
// how do I pass the cursor?
getContext().startActivity(intent);
}
}
Activity.onCreate() {
// how do I retrieve the cursor?
setContentView(...);
}
即如果query()
没有返回任何数据,我想错过启动
Activity
,并允许广播消息正常通过.
i.e. if the query()
returns no data I want to miss out launching the
Activity
, and allow the Broadcast message to fall through as normal.
如果query()
确实返回了数据,我希望将Cursor
提供给
Activity
,这样我就不必再去查询数据了.
If the query()
does return data, I want that Cursor
to be supplied to
the Activity
, so that I don't have to go and query for the data again.
依次,Activity
具有自己的用户界面,用户需要对其进行响应.
In turn, the Activity
has its own UI which the user needs to respond to.
这可能吗?
推荐答案
您想要的东西有些困难,对我而言,效率很低.我建议您使用第一种方法,但是当您在活动中加载Cursor时,请检查是否没有数据,然后退出活动.
What you want is somewhat difficult and to me, rather inefficient. I would propose that you use the first alternative, but when you load the Cursor in the activity, check if there is no data, and then exit the activity.
BroadcastReceiver.onReceive() {
Intent intent = new Intent(...);
intent.setData(...); // set a single String data
context.startActivity(intent);
}
Activity.onCreate() {
String value = intent.getData(); // get the String data
Cursor = ContentProvider.query(search);
if(cursor.isEmpty() ...){
finish();
return;
}
...
setContentView(...);
}
这将具有完全相同的效果,仅将光标加载一次,并且仅当光标中存在某些内容时才显示活动.唯一的额外开销是无论如何都将触发该意图,但这并不是很费力:)
This will have the exact same effect, the cursor will only be loaded once, and the activity will only be displayed if something exists in the cursor. The only extra overhead is that the intent is fired no matter what, but that's not exactly taxing :)
请注意,不会有任何闪烁,也不会发生任何事情,Android在onCreate()中处理完成的情况(我相信onStart和onResume也是如此),以便用户永远不知道它发生了.
Note that there won't be any flicker or anything either, Android handles the case of calling finish in onCreate() (I believe onStart and onResume as well) so that the user never knows it happened.
这篇关于Android BroadcastReceiver,ContentProvider和Activity之间的数据流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!