简体   繁体   中英

Android: How to get context of calling activity in an IntentService?

If I call

Intent intent = new Intent(ReadingActivity.this, AdService.class);
startService(intent);       

from within the onCreate method of MyActivity class, how do I get access to MyActivity.this from inside the onHandleIntent() method of the IntentService class

@Override
protected void onHandleIntent(Intent arg0) {
    // TODO Auto-generated method stub
    ((BookLib) getApplication()).createAd(I need to pass the calling activities context here);
}

how do I get access to MyActivity.this from inside the onHandleIntent method of the IntentService class

You don't.

Move createAd() into the activity. If time is an issue, use an AsyncTask rather than an IntentService .

An IntentService is mostly for cases where you want work to go on decoupled from any activity (eg, a file download that should continue even if the user leaves your UI to go on to do something else).

It seems to me like you're trying to do bi-directional communication with your Activity and Service . Instead of sending an Intent to your service, consider binding to it instead.

EDIT: Responding to CommonsWare's comments:

Where is the problem with binding to an IntentService ? I've shipped apps that work just fine that contain a bound IntentService . You've provided no evidence to back up your claim.

From here :

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy() .

The docs clearly indicate that the system supports simultaneous binding and starting. Using an IntentService over a regular Service doesn't change this. Even if you explicitly stop the service after processing an Intent , Android leaves it running as long as something is still bound to it.

Besides, depending on what OP is trying to do, IntentService might no longer be necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM