Dino Rino
Dino Rino

Reputation: 55

Pass a Context an IntentService

I have this code:

Intent publishIntent = new Intent(HistoryDoneVsPlanned.this, MyIntentService.class);
publishIntent.putExtra(HistoryMap.KEY_WORKOUT_ID, workoutId);

where HistoryDoneVsPlanned is my current Activity and MyIntetService is a IntentService.

and my goal is pass the current context of the activity at the intentService like this:

publishIntent.putExtra("CONTEXT", HistoryDoneVsPlanned.this);

but is not possible.

Is a good practice? I need make the Toast and notification into another class (not Activity) and I need the context of the activity.

Upvotes: 3

Views: 10983

Answers (2)

Pradip
Pradip

Reputation: 3177

When you are using the context in cross-activity usage, you should not bound the Activity context to the action, since then even if the activity is destroyed, it will not be garbage-collected, as it is still referenced from the running task. In those cases, you should use the Application context. For more look at the android developer blog.

Upvotes: 1

Pankaj Kumar
Pankaj Kumar

Reputation: 82958

Is a good practice? I need make the Toast and notification into another class (not Activity) and I need the context of the activity.

No. This is not a good practice. You should show notification from Services. But it depends on application behavior you can do also.

Case 1: If Service/ Intent Service running and doing task into background..

You should show notification instead of Toast. Read How to show notification from background service?

Case 2: If Service/ Intent Service running and doing task into background, but returns result to an Activity (Which means User is present for your app)

You can show Toast in this case. Read Show toast at current Activity from service

Note : And do not pass context via Intent to MyIntentService. You can get Context into MyIntentService also by doing MyIntentService.this. And this is because all Android Components overrides Context class, on of them is IntentService.

Upvotes: 4

Related Questions