简体   繁体   中英

GetActivity from IntentService in Android

I have an IntentService class

public class eventoTimer extends IntentService {}

public Utilities(Activity activity) {
        this.activity = activity;
        this.session = new UserSessionManager(this.activity);
}

And I need to instantiate the Utilities class with an Activity but I do not know how to call the getActivity from the IntentService

And I need to instantiate the Utilities class with an Activity but I do not know how to call the getActivity from the IntentService

You can't. For example, there is no requirement that there be an activity, as the user could have destroyed your activity while your IntentService is doing its work.

Either:

  • Change Utilities to take a Context , rather than an Activity (so you can pass in the IntentService to the Utilities constructor), or

  • Use an event bus (eg, LocalBroadcastManager , greenrobot's EventBus) to send a message to your activity, if it exists, to have it do something, or

  • Get rid of the IntentService , if it is so tightly coupled to the activity, and do something else for your background threading (eg, AsyncTask )

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