如何从任何地方获取上下文?
2022-09-01 02:52:25
						在 Android 中,有没有办法以静态方式获取应用的上下文?例如,从后台线程中检索它。
谢谢
在 Android 中,有没有办法以静态方式获取应用的上下文?例如,从后台线程中检索它。
谢谢
最简单(和正确)的方法是:
定义新类
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 并放置
<application
    android:name="com.example.app.MyApp"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    .......
    <activity
        ......
然后从任何你可以打电话的地方
MyApp.getContext();
希望它有帮助