如何从任何地方的语境?语境、地方

2023-09-06 00:15:36 作者:薰铱草De悆稥

在Android中,有没有什么办法让一个静态的方式应用的背景下?例如,从后台线程取回它。

In Android, is there any way to get the context of the application of a static way? For example to retrieving it from a background thread.

感谢

推荐答案

最简单的(正确)的方法是:

The easiest (and correct) way is:

定义一个新类

public class MyApp extends Application {
    private static MyApp instance;

    public static MyApp getInstance() {
        return instance;
    }

    public static Context getContext(){
        return instance;
        // or return instance.getApplicationContext();
    }

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

然后在你的清单,你需要把这个类添加到名称字段的应用程序选项卡。或编辑XML,并把

Then in your manifest you need to add this class to the "Name" field at the "Application" tab. Or edit the xml and put

<application
    android:name="com.example.app.MyApp"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    .......
    <activity
        ......

,然后从任何地方,你可以叫

and then from anywhere you can call

MyApp.getContext();

希望它可以帮助

Hope it helps