I have an asynctask that does something, when its done, I want it to broadcast that its done.
usually I would do : context.sendBroadcast(new Intent(MYINTENT));
however asynctask has no context. I've seen a few answers to this questions suggesting sending a reference to the context of the app's activity to the asynctask. but that reference is bad if the user rotates the screen. and manually maintaining the reference is a bad solution (requires too much from the activity creating the asynctask, which I do not control). now the questions are:
1) why is android set up like that ? why do I even need a context to send a broadcast when broadcasts can be registered for and handled by other contexts ?
2) is there a good solution to this problem ? (good = requires as little as possible from the activity creating the asynctask, survives rotations, etc..).
The context that you are using in your AsyncTask right now is the context of your current Activity. By default a screen rotation will destroy the current instance of that Activity and create a new one. This is (even if it may not seem so at first) intended behavior. The reason for this is that you may want to have different resources (layouts, drawables, etc) for different screen orientations. In order to apply those potentially different resources Android will recreate the Activity on every rotation.
You can counteract that by setting the android:configChanges
attribute in your AndroidManifest.xml
file but in your case this solution is not recommended.
The proper way of dealing with this problem is to pass the Application Context to the AsyncTask
instead of your Activity (Activity
inherits from Context
). You can do that by calling getApplicationContext()
from the instance of your Activity.
Your applications context will persist events such as screen rotation and lives until the system kills the app.
As to why you need an instance of Context to do basic tasks:
Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
This is how the official documentation defines a Context
.
Maybe someone can explain this better but for myself this definition is sufficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With