【问题标题】:Android: Access Data from a Service of another applicationAndroid:从另一个应用程序的服务访问数据
【发布时间】:2015-11-23 10:18:48
【问题描述】:

有两个应用程序,App1 和 App2。我在 App1 中启动了这样的服务:

Intent sendIntent = new Intent(this, HelloService.class);
sendIntent.setAction("getDataFromApp1");
sendIntent.putExtra("dataKey", "This is data I am sending.");
startService(sendIntent);

现在我想从该服务中获取数据[我使用putExtra() 在 Intent 中设置的 String 对象] 并将其显示在 App2 中。

所以我的问题是如何访问由另一个应用程序创建的服务中的数据。我已经在 Manifest File 中使用 android:exported=true 声明了该服务。

【问题讨论】:

  • 然后使用“绑定服务”模式
  • 我是android新手,不知道绑定服务
  • 所以了解它,更多here

标签: java android


【解决方案1】:

您需要在 App1 中公开内容提供程序,该提供程序提供可在 App2 中使用的数据。 是的,您需要确保将 export 设置为 true。

您可以开始使用它。 http://developer.android.com/guide/topics/providers/content-provider-creating.html

【讨论】:

  • 我已在 App1 中使用 putExtra() 将数据放入意图中。所以我需要在 App2 中提取该数据。
  • 好的,如果 App1 正在向 App2“提供”数据,那么这应该没问题,但如果 App2 正在“请求”数据,那么您将需要内容提供者。请改写你的问题。它给人以“请求”的感觉。
【解决方案2】:

您可以通过使用Intent's 来完成此操作。您可以将所需的任何数据附加到Intent,并且可以在任何应用中侦听特定类型的Intent

例如,您可以像这样发送Intent

Intent sendIntent = new Intent();
sendIntent.setAction(your.custom.action.for.app.two);
sendIntent.putExtra("dataKey", "Pass this text to app two.");
startActivity(sendIntent);

然后在您的第二个应用中,将意图过滤器附加到您希望在您的AndroidManifest.xml 中启动的Activity,如下所示:

<intent-filter>
        <action android:name="your.custom.action.for.app.two" />
</intent-filter>

然后在Activity 中检查您的onCreate,如果它是通过Intent 启动的,并像这样处理数据:

 if (getIntent().getAction().equals(your.custom.action.for.app.two) {
     String yourText = getIntent().getStringExtra("dataKey");
 }

您还需要考虑许多其他事项。比如检查你的第二个应用程序是否存在于用户手机上,如果应用程序没有唤醒怎么办?请参阅here 了解更多信息。

【讨论】:

  • your.custom.action.for.app.two 这是字符串名还是包名
  • 这可以是任何你喜欢的,它只是一个你需要在另一端匹配的键,就像一个变量名。
  • 我想通过服务而不是活动传递数据
  • 您可以发送将通过服务接收的广播,只需将 startActivity 交换为 sendBroadcast 并将意图过滤器附加到服务。
猜你喜欢
  • 1970-01-01
  • 2012-05-29
  • 2012-06-12
  • 2015-05-30
  • 2016-07-08
  • 1970-01-01
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
相关资源
最近更新 更多