InfernumDeus InfernumDeus - 2 months ago 6
Android Question

How to perform some actions before letting user to do anything?

I need to perform some actions before application actually started.

I tried this but can't reach breakpoint:

public class MyApplication : Android.App.Application {
public MyApplication(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer) { }

public override void OnCreate() {
base.OnCreate();
int test = 1; //breakpoint
}
}


Am I doing something wrong? Or here is some debugger problem?

Answer

The key item here is to "Register" your custom Application class by using the [Android.App.Application] attribute. Secondly you need to provide an OnCreate override to ensure the custom application class's constructor is invoked. Otherwise without the [Application] attribute, we do not register the custom <application> element in the AndroidManifest.xml. Rather we use the default android.app.Application instead:

<application android:label="App6" android:name="android.app.Application" android:allowBackup="true" android:icon="@drawable/icon" android:debuggable="true">

Thus if we register using the [Application] attribute, we then will see our custom application class used instead:

<application android:label="App6" android:name="md50033386ba710bcf156abf7e9c48d30ef.MyApplication" android:allowBackup="true" android:icon="@drawable/icon" android:debuggable="true">

Here's a complete working example of this:

[Application] //Name is typically a good idea as well
public class MyApplication : Application
{
    public MyApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
    { }
    public override void OnCreate()
    {
            base.OnCreate();
            int myInt = 1;
    }
}

enter image description here

Without a name defined in the comment above, you'll get a md5 hashed named instead.

There's a few notes in our Architecture docs that might be beneficial here as well:

https://developer.xamarin.com/guides/android/under_the_hood/architecture/#Application_Startup

Comments