开发者

Android: Passing data between service and activity

So I'm getting really confused on how to do this whole thing and I was hoping someone could break it down for me a little bit.

I have a service that should always be running, and at certain times it needs to alert the user that a task is to be completed(probably through a notification bar icon). When the user accepts the task, the service needs to look into the local database, construct some non primitive objects, and give them to the activity that it just started.

I have looked all over and gotten very confused as to a proper approach so I have a few questions to help me wrap my head around it.

  1. If an activity creates a local SQLite database can the service and activities of that application access that same database later?

  2. Does the service and activity need to be in the same or separate packages? I would think no but for some reason I remember seeing something about this elsewhere.

  3. How would I do the data transmission from the service to the activity? I was thinking a content provider but it seems like there sh开发者_如何学运维ould be an easier way for the service to just hand off the data. Similar to an Intent but for non primitives.

Thanks in advance.


  1. If the Service and Activity classes are in the same package, I believe they should be able to access the same private storage space.

  2. I would put them in the same package since they are part of the same overall application structure.

  3. Bundle the data into an Intent's extras as Key-value pairs and start the activity.


Intent intent = new Intent(this, SecondActivity.class);
Bundle b = new Bundle();

// see Bundle.putInt, etc.
// Bundle.putSerializable for full Objects (careful there)
b.putXXXXX("key", ITEM);  
intent.putExtras(b);
startActivity(intent);

// -- later, in Activity
Bundle b = this.getIntent().getExtras();
int i = b.getInt("key");


In the same application, services and activities can access the same Sqlite database. I'd suggest using a sqlite db. For simplicity, set up your service connection as a local, so you don't need the AIDL interfaces and inter-process communication stuff.

From a service, to notify the user, use the NotificationManager. You can pass a serializable object from your service to an intent, then to the activity that gets started, but I'd suggest passing a db ID instead.

We have built a new Android ORM tool that you can use for this. It includes prototype Activity and Service classes that you can use to build your app. I don't have an example app yet that uses the service, but I'll code that one next and get it up ASAP.

See...

http://ormlite.com/

And my blog...

http://touchlabblog.tumblr.com/

I currently do some pretty heavy db stuff in the app I'm working on. A service checks with a server for updates, and essentially does what you're looking to do. Its all pretty simple stuff.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜