Can an Application call methods directly on an Activity?
We have an application:
public class MyApplication extends Application {
...
}
containing a main Activity called Start, configured in AndroidManifest.xml
MyApplication starts an AsyncTask, which loads data.
When the AsyncTask returns, the Application wants to notify Start,
but MyApplication seems 开发者_如何学编程to have no reference to Start.Can an Application call methods directly on an Activity ?
Can an Application call methods directly on an Activity ?
Sure. You will wind up with memory leaks if you are not careful, and I would consider what you are describing to be poor programming. At minimum, use a listener or observer pattern, as @fiction suggests.
When the AsyncTask returns, the Application wants to notify Start, but MyApplication seems to have no reference to Start.
Then write the appropriate Java code to have Start
register some sort of listener (or observer, to use @fiction's term) with MyApplication
for use with your AsyncTask
. Just be sure to unregister that listener, or use a SoftReference
or something, to ensure that MyApplication
does not hold a strong reference to Start
past Start
's lifetime.
And, of course, you will need to deal with the fact that you could have several instances of Start
.
It's quite odd to me to start an AsyncTask in an Application onStart(). This means that from the instant your user wants to start your app and until the completion of data loading, you won't give the user any feedback about what your application is doing. And then, after a while, your Activity would popup.
In addition, don't forget that Application.onStart() is called only once in your application lifecycle until the system decides to kill it or a force close happens.
I would personaly launch an Activity first, and in the Activity.onCreate(), after initializing a minimum set of UI components indicating that something is happening, I would start the AsyncTask to retrieve data. If things are done this way you can even quite easily display a progressbar updated by your AsyncTask.
精彩评论