How to get the Context object in the static utility class in Android

Context needs to be provided when accessing resources in an Android program. Generally speaking, only in various components (Activity, Provider, etc.) can you easily use the API to obtain the Context object. If you need to use the Context object when writing a tool class, you can use the following way to obtain.

We can achieve this by customizing an Application class.

Create a new class inherited from Application under the src/main/java/ package, called MyApplication here, and the directory structure is as follows: it must be in the java directory, otherwise it will not be found

 MyApplication

package com.example.cashbook;

import android.app.Application;
import android.content.Context;

/**
 * @author wh445306
 * @version 1.0
 * @Description MyApplication
 * @Date 2023-06-16 1:59
 */

public class MyApplication extends Application {
    public static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }
}

Then open AndroidManifest.xml, add

     <application
         android:name=".MyApplication"

Then we can pass in any tool class

MyApplication.context

Get and use:

Guess you like

Origin blog.csdn.net/wh445306/article/details/131263554