【问题标题】:Pass String from activity to service?将字符串从活动传递到服务?
【发布时间】:2011-08-20 07:46:42
【问题描述】:

我熟悉使用 putExtra 和 getExtra 方法将数组从一个活动传递到另一个活动的方法。但是,每当我尝试从服务中获取它时,以下代码都不起作用:

Bundle b = this.getIntent().getExtras();
String Array = b.getStringArray("paths");

它无法识别以下内容:

this.getIntent().getExtras();

有什么想法吗?

编辑

在活动类中我有以下内容:

    toService = new Intent();
    toService.setClass(this, Service.class);
    toService.putExtra("paths",Array);

在服务类中:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    Bundle extras = intent.getExtras();
    if(extras!=null)
    {
        Paths = extras.getStringArray("paths");
        Toast.makeText(protectionService.this, Paths[0], Toast.LENGTH_SHORT).show();
    }

    return 0;
}

什么都没有出现,因为路径显然没有被分配。

Paths = extras.getStringArray("paths");

好像没用。

【问题讨论】:

  • “不起作用”是什么意思?它是否崩溃,给出错误的结果等
  • 我的意思是服务类无法识别代码 this.getIntent()...

标签: android arrays service android-activity


【解决方案1】:

您试图在哪里访问 getIntent?

这是我编写的一个使用 getExtras 的程序的 sn-p:

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Bundle extras = intent.getExtras();
    if (extras != null) {
        // Do what you want 
      }
}

但是,onStart 现在已被弃用,因此您应该真正使用onStartCommand。 您将意图作为参数之一。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  handleCommand(intent);
  // We want this service to continue running until it is explicitly
  // stopped, so return sticky.
  return START_STICKY;
}

否则,您可以使用AIDL、首选项或此处​​回答的任何其他示例:How to access a variable present in a service

同样的问题已经回答Android: how to get the intent received by a service?

编辑: 如果你用这个

toService = new Intent();
toService.setClass(this, Service.class);
toService.putExtra("array",Array);

你需要用相同的key来获取extra,这里的key是"array"

Paths = extras.getStringArray("array");

【讨论】:

  • 我已经编辑了第一篇文章。所以基本上如果 extras 不等于 null 那么我可以使用 extras.getStringArray("array") ,因为它在活动中使用?
  • 是的,您不需要任何 getIntent(),因为您将意图作为 onStartCommand 中的参数之一。所以在onStartCommand中你只需要使用intent.getExtras()。您应该检查它们是否不为空
  • 我在原帖中添加了另一部分代码,请查看。 Paths = extras.getStringArray("paths");不工作。
  • 您使用的是哪个 API 级别?我编辑了我的答案,当您放置附加组件和获取附加组件时,您需要拥有相同的密钥。
  • 这是第 10 级。我确实有相同的钥匙。两边都是“路径”。
猜你喜欢
  • 2012-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多