问题
I'm deriving a custom application from android.app.Application and I can't get its onCreate event being fired. Here's the implementation
import android.app.Application;
public class MyApplication extends Application {
public MyApplication() {
super();
}
@Override
public void onCreate() {
super.onCreate();
}
}
And here's how I'm using it:
MyApplication ctrl = new MyApplication();
回答1:
Add following in your AndroidManifest.xml
<application
android:name="MyApplication"
android:debuggable="true"
android:icon="@drawable/icon"
android:label="@string/app_name">
</application>
then your onCreate()
will get fired.
回答2:
Very simple
In your AndroidManifest.xml
, within the application
tag enter the name of your Application
sub-class with it's path under the android:name
attribute.
Example:
<application
...
android:name=".models.custom.BaseApplication"
...
> ... </application>
回答3:
I had this issue and found that in my case that the whole issue was phone side. I rebooted the phone and that fixed the issue.
回答4:
Don't construct it, get it from Context
.
For example from Activity
:
MyApplication ctrl = (MyApplication)getApplicationContext();
More info: Context.getApplicationContext()
Documentation says that onCreate()
is
Called when the application is starting, before any other application objects have been created
回答5:
You don't actually create instances of your Activities with the new
operator. Instead you start an Intent like this:
Intent start = new Intent(context, Classname.class);
context.startActivity(start);
When creating an object with the new
operator, then onCreate
never will be called.
[EDIT] When creating Applications with the new
operator onCreate
won't be called either[/EDIT]
[EDIT2] You could create a static method that returns the application like this:
public static MyApplication getApp() {
return mInstance;
}
[/EDIT2]
回答6:
As Balaji Mentioned if your still facing issue even after mentioning class name under application tag
<application
android:name="MyApplication"
android:debuggable="true"
android:icon="@drawable/icon"
android:label="@string/app_name"> </application>
Then try this:
Try and disabling Instant Run and then clean project and Rebuild it and then run again. It worked for me. Thanks.
来源:https://stackoverflow.com/questions/6858158/custom-android-app-application-not-firing-oncreate-event