public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Obtain the application context Context context = getApplicationContext(); Toast.makeText(context, "Hello world!", Toast.LENGTH_SHORT).show(); } }
public class MyApplication extends Application { private static MyApplication instance; public static synchronized MyApplication getInstance() { return instance; } @Override public void onCreate() { super.onCreate(); instance = this; } }In this example, we create a custom Application class that extends the default Application class. We store an instance of the class inside a singleton for easy access from anywhere in the app. This is useful for global initialization or configuration that should happen once when the app starts up. Package Library: The package library for the getApplicationContext() method is android.app. This package provides core application classes, including the Application class used in the above examples.