Reputation: 53
How to pass context
to a service with putExtra
?
The problem is : android.os.Application
cannot be cast to java.io.Serializable
How to solve this problem?
// main activity
public void btnGetLocate() {
Intent intent = new Intent(this, Sleeper.class);
intent.putExtra("context", (Serializable) getApplicationContext());
startService(intent);
}
// another file
public class MyService extends IntentService {
public Sleeper() {
super("MyService");
}
protected void onHandleIntent(Intent intent) {
Context context = (Context) intent.getExtras().getSerializable("context"); // make Error, main problem
MyClass mc = new MyClass(context);
...
}
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "destroyed"), Toast.LENGTH_SHORT).show();
}
}
Upvotes: 3
Views: 12189
Reputation: 16363
You should bound/bind Service
- in that case you'll be able to have reference to Service
object in your Activity
. Using those reference it's pretty easy to set/send Context
.
Upvotes: 0
Reputation: 1007524
You cannot do that, nor do you need to. Not only is Service
a Context
, but Service
can call getApplicationContext()
to get the Application
object if that is what you truly need. Do not pass in extras things that the service can get on its own.
Upvotes: 8
Reputation: 2663
You can't do it (use context as extra) because this class Application doesn't implements Serializable interface.
The easy way to do it is display a dialog with title *Getting location..." and do the location request inside current activity. Then, when you get the location, dismiss the dialog.
You can follow this Google tutorial, which uses Google Play Services, to get location in an easy way.
Good luck!
Upvotes: 0