Reputation: 133
I am doing some Android programming and I want to create a runnable that accepts intents. I understand that the general way of creating a runnable is:
Runnable R1 = new Runnable(){ Code };
What I want is for my runnable to accept an intention as a parameter or input. The runnable then uses the intention for something else. I imagine that I would look something like this:
Runnable R1 = new Runnable(Intent i1){ Code };
I have tried this and variations of this and cannot get it to compile. How do I do this?
Upvotes: 0
Views: 712
Reputation: 23001
The answer to this depends on whether you want to pass in the Intent at the time the Runnable is constructed, or when the run is called. For the former case, user2246674 has provided an excellent answer.
However, if you want to do the latter, you're going to need to create an interface that looks sort of like Runnable
but isn't.
public interface RunnableWithIntent {
void run(Intent intent);
}
You'd then instantiate your "runnable" interface like this:
RunnableWithIntent r = new RunnableWithIntent() {
public void run(Intent intent) {
// do something with the intent
}
};
And call it like this:
Intent intent = ...
r.run(intent);
Note that this class can't be used anywhere you would use a regular Runnable object. It merely follows a similar usage pattern.
Upvotes: 0
Reputation: 7719
To accept parameters, a new class must be created that conforms to Runnable so that the parameters can be passed to (and used usefully in) the constructor. An alternative approach to capture state which is useful with anonymous Runnable objects is to access final
variables in the lexical scope.
With a new class and a constructor that accepts parameters and stores the values for later use:
class RoadRunner implements Runnable {
String acmeWidget;
public RoadRunner (string acmeWidget) {
this.acmeWidget = acmeWidget;
}
public void run () {
evadeCleverPlan(acmeWidget);
}
}
void doIt () {
Runnable r = new RoadRunner("Fast Rocket");
// do something with runnable
}
(If RoadRunner
is an inner class - that is a non-static nested class - it can also access instance members of the enclosing type.)
With an anonymous Runnable and a "poor man's closure":
void doItAnon () {
final String acmeWidget = "TNT";
Runnable r = new Runnable () {
public void run () {
evadeCleverPlan(acmeWidget);
}
};
// do something with runnable
}
(This anonymous Runnable can also access instance members of the containing type as anonymous classes are inner classes.)
Upvotes: 2