Android: Passing data between service and activity

后端 未结 2 726
一生所求
一生所求 2020-12-23 22:41

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

相关标签:
2条回答
  • 2020-12-23 23:00
    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");
    
    0 讨论(0)
  • 2020-12-23 23:16

    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 讨论(0)
提交回复
热议问题