3

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();  
    } 
}
stealthjong
  • 10,858
  • 13
  • 45
  • 84
Armpc
  • 53
  • 1
  • 2
  • 11
  • 1
    why do you want to do that? – pskink Sep 05 '14 at 12:36
  • possible duplicate of [Get Context in a Service](http://stackoverflow.com/questions/6446221/get-context-in-a-service) – 2Dee Sep 05 '14 at 12:37
  • @pskink because gps locator – Armpc Sep 05 '14 at 12:39
  • Try another solution – Morteza Soleimani Sep 05 '14 at 12:50
  • please write example – Armpc Sep 05 '14 at 12:52
  • @2Dee I check it, but make fatal error. – Armpc Sep 05 '14 at 12:55
  • GPSTracker gps = new GPSTracker(context); // check if GPS enabled if (gps.canGetLocation()) { double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); // \n is for new line Toast.makeText(getApplicationContext(),"Your Location - \nLat: " + latitude + "\nLong: "+ longitude, Toast.LENGTH_LONG).show(); } else { // can't get location // GPS or Network is not enabled // Ask user to enable GPS/network in settings gps.showSettingsAlert(); } – Armpc Sep 05 '14 at 12:55
  • Please edit the question to provide additional code. It's difficult to read in comments. – Mike M. Sep 05 '14 at 13:01

3 Answers3

8

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

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!

jmvivo
  • 2,653
  • 1
  • 16
  • 20
0

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.

See here

Barmaley
  • 16,638
  • 18
  • 73
  • 146