I am familiar with the method of passing arrays from one activity to another activity using putExtra and getExtra methods. However, whenever I try to get it from a service the following code doesn't work:
Bundle b = this.getIntent().getExtras();
String Array = b.getStringArray("paths");
It is not recognizing the following:
this.getIntent().getExtras();
Any ideas?
EDIT
in the activity class I have the following:
toService = new Intent();
toService.setClass(this, Service.class);
toService.putExtra("paths",Array);
in the service class:
@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()开发者_StackOverflow社区;
}
return 0;
}
Nothing is appearing since Paths is not being assigned apparently.
Paths = extras.getStringArray("paths");
Doesn't seem to work.
Where are you trying to access getIntent?
Here is a snippet from a program I have written which uses the getExtras:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Bundle extras = intent.getExtras();
if (extras != null) {
// Do what you want
}
}
However, onStart is now deprecated so you should really use onStartCommand. You get the intent as one of the parameters.
@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;
}
Otherwise you could use AIDL, Preferences or any other example answered here: How to access a variable present in a service
Same question has already been answered Android: how to get the intent received by a service?
Edit: If you use this
toService = new Intent();
toService.setClass(this, Service.class);
toService.putExtra("array",Array);
You need to get the extras with the same key, here the key is "array"
Paths = extras.getStringArray("array");
精彩评论