我熟悉使用 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/