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

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

问题描述

所以我对如何做这整件事感到非常困惑,我希望有人可以为我分解一下.

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. 如果活动创建了本地 SQLite 数据库,那么该应用程序的服务和活动以后是否可以访问同一个数据库?

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

服务和活动是否需要在同一个或不同的包中?我认为不会,但出于某种原因,我记得在其他地方看到过有关此内容的内容.

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.

我将如何进行从服务到活动的数据传输?我在考虑内容提供商,但似乎应该有一种更简单的方法让服务只传递数据.类似于 Intent,但用于非原语.

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.

提前致谢.

推荐答案

  1. 如果 Service 和 Activity 类在同一个包中,我相信它们应该能够访问相同的私有存储空间.

  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.

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

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

将数据以键值对的形式打包到 Intent 的 extras 中并开始活动.

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

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

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