Get Activity's Reference From A Service
Solution 1:
You didn't explain why you need this. But this is definitely bad design. Storing references to Activity is the first thing you shouldn't do with activities. Well, you can, but you must track Activity lifecycle and release the reference after its onDestroy()
is called. If you are not doing this, you'll get a memory leak (when configuration changes, for example). And, well, after onDestroy()
is called, Activity is considered dead and is most likely useless anyway.
So just don't store the reference in Service. Describe what you need to achieve instead. I'm sure there are better alternatives out there.
UPDATE
Ok, so you do not actually need reference to Activity. Instead you need reference to Context (which in your case should be ApplicationContext to not keep reference to Activity or any other component for that matter).
Assuming you have a separate class that handles WebService request:
classWebService
{
privatefinal Context mContext;
publicWebService(Context ctx)
{
//The only context that is safe to keep without tracking its lifetime//is application context. Activity context and Service context can expire//and we do not want to keep reference to them and prevent //GC from recycling the memory.
mContext = ctx.getApplicationContext();
}
publicvoidsomeFunc(String filename)throws IOException
{
InputStreamiS= mContext.getAssets().open("www/"+filename);
}
}
Now you can create & use WebService instance from Service
(which is recommended for such background tasks) or even from Activity
(which is much trickier to get right when web service calls or long background tasks are involved).
An example with Service
:
classMyServiceextendsService
{
WebService mWs;
@OverridepublicvoidonCreate()
{
super.onCreate();
mWs = newWebService(this);
//you now can call mWs.someFunc() in separate thread to load data from assets.
}
@Overridepublic IBinder onBind(Intent intent)
{
returnnull;
}
}
Solution 2:
To communicate between your service and activity you should use AIDL. More info on this link:
EDIT: (Thanks Renan Malke Stigliani) http://developer.android.com/guide/components/aidl.html
Solution 3:
The AIDL is overkill unless the activity and service are in seperate apks.
Just use a binder to a local service. (full example here: http://developer.android.com/reference/android/app/Service.html)
publicclassLocalBinderextendsBinder {
LocalService getService() {
return LocalService.this;
}
}
Solution 4:
Agree with inazaruk's comments. But, In terms of communicating between an Activity and a Service, you have a few choices - AIDL (as mentioned above), Messenger, BroadcastReicever, etc. The Messenger method is similar to AIDL but doesn't require you to define the interfaces. You can start here:
Post a Comment for "Get Activity's Reference From A Service"