Reputation: 55
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
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
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