【问题标题】:Connection between Activity and ServiceActivity 和 Service 之间的连接
【发布时间】:2014-05-04 21:30:03
【问题描述】:

我有一个带有 EditText 和一些复选框的 Activity。用户插入文本后,文本应发送到服务,服务将在后台运行,不时显示 Toast。

我很难弄清楚如何将数据(用户通过 Activity 输入的字符串和布尔值)发送到服务

【问题讨论】:

  • 服务的功能是什么?是通过网络进行通信吗?
  • 服务只是不时地显示一个 Toast,即使在用户关闭应用程序之后也是如此。

标签: java android android-activity service


【解决方案1】:

在 Activity 上使用 Intent 将值放入 puExtra

Intent intent = new Intent(current.this, YourClass.class);
intent.putextra("keyName","value"); 

然后调用 StartService 以便调用 OnStart 方法。 在服务中通过使用意图获取 OnStart 中的值

Bundle extras = getIntent().getExtras();
   if (extras != null) 
   {
     String value = extras.getString("key");
   }

【讨论】:

    【解决方案2】:

    你看过Android Documentation For Services吗?

    它解释了您需要知道的一切以及更多内容:)

    (提示:您必须将 Intent 传递给 OnStartCommand())

    如果您在第一个结果中搜索“将意图传递给 android 中的服务”,您会发现:

    Pass data from Activity to Service using an Intent

    【讨论】:

    • 您也可以选择使用 SharedPreferences。可能是 OP 上手的一种更简单的方法,因为它涉及的内容更少且更直观。
    • mbs 你知道 SharedPreferences 用法的一个例子吗?谢谢
    • Martin Marconcini 我看了看,但它准确地指向了我想去的地方。立即阅读您的链接,谢谢
    猜你喜欢
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多