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:configChangesattribute in yourAndroidManifest.xmlfile 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
AsyncTaskinstead of your Activity (Activityinherits fromContext). You can do that by callinggetApplicationContext()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:
This is how the official documentation defines a
Context.Maybe someone can explain this better but for myself this definition is sufficient.