Dataflow between Android BroadcastReceiver, ContentProvider, and Activity?

被刻印的时光 ゝ 提交于 2019-12-06 02:52:19

问题


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

it goes:

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

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.

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.

In turn, the Activity has its own UI which the user needs to respond to.

Is this possible?


回答1:


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 :)

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.




回答2:


You'll need to find or make a Cursor that's Serializable or Parcelable (and then use intent.setExtra()). Or maybe it's possible to instead read all the data in as a parcel and pass that on to the Activity?



来源:https://stackoverflow.com/questions/662344/dataflow-between-android-broadcastreceiver-contentprovider-and-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!