安卓:服务和活动之​​间传递数据 [英] Android: Passing data between service and activity

查看:406
本文介绍了安卓:服务和活动之​​间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我得到关于如何做这件事,我希望有人能打破它,我有点真糊涂。

我有应始终运行的服务,并且在某些时候,需要以提醒一个任务是要完成(可能通过一个通知栏图标)的用户。当用户接受任务,服务需要寻找到本地数据库,建立一些非基本对象,并给他们,这只是开始活动。

我已经找遍了,并得到非常混乱,以适当的解决办法,所以我有几个问题,帮我环绕它我的头。

  1. 如果一个活动创建一个本地SQLite数据库可以在服务与该应用程序的访问活动同一个数据库以后呢?

  2. 是否服务和活动需要在相同或单独的包?我认为没有,但由于某种原因,我记得看到一些关于这在其他地方。

  3. 如何将我从服务活动相关的数据传输?我在想一个内容提供商,但它好像应该是服务只是手头宽裕的数据更简单的方法。类似的意向,但对于非原语。

在此先感谢。

解决方案
  1. 如果服务和活动类在同一个包,我相信他们应该能够访问相同的专用存储空间。

  2. 我把它们放在同一个包,因为它们是同一个应用程序的整体结构的一部分。

  3. 捆绑数据到一个Intent的额外的键值对,并开始活动。


 意向意图=新的意图(这一点,SecondActivity.class);
叠B =新包();

//看到Bundle.putInt等。
// Bundle.putSerializable全对象(小心有)
b.putXXXXX(钥匙,项目);
intent.putExtras(B);
startActivity(意向);

//  - 之后,在活动
叠B = this.getIntent()getExtras()。
INT I = b.getInt(钥匙);
 

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 should 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");

这篇关于安卓:服务和活动之​​间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆