android - 将字符串从 Activity 传递到服务?

标签 android arrays service android-activity

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

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

它无法识别以下内容:

this.getIntent().getExtras();

有什么想法吗?

编辑

在 Activity 类中我有以下内容:

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

好像不行。

最佳答案

您要在哪里访问 getIntent?

这是我编写的一个使用 getExtras 的程序的 fragment :

@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 . 您将 Intent 作为参数之一。

@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获取extras,这里key是“array”

Paths = extras.getStringArray("array");

关于android - 将字符串从 Activity 传递到服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7130512/

相关文章:

android - 使用 volley 以 json 格式将数据发布到服务器

java - Guava 函数 toByteArray() 返回 null?

arrays - 阵列平均速度和最高速度 "CoreLocation"

arrays - 在shell脚本中排序

Android 服务没有立即启动

service - 由域帐户运行的 Windows 服务在完全控制时无法访问文件

android - 如何从平均海平面计算海拔高度

java - 如何从具有 gradle 依赖性的代码创建 Android 库?

c# - 在 C# 中,使用 for 循环迭代数组是线程安全操作吗?使用 foreach 循环迭代 IEnumerable<T> 怎么样?

javascript - Angular - 将数组信息从一个 Controller 传递到另一个 Controller