简体   繁体   English

在非活动中需要上下文

[英]Need context in non-activity

I have a MainActivity, a class called FailedPasswordHandler and a CameraHandler. 我有一个MainActivity,一个名为FailedPasswordHandler和CameraHandler的类。 The FailedPasswordHandler implements the DeviceAdminReceiver. FailedPasswordHandler实现DeviceAdminReceiver。 Now I want to create a CameraHandler object in the FailedPasswordHandler class, but it requires a context argument. 现在,我想在FailedPasswordHandler类中创建一个CameraHandler对象,但是它需要一个上下文参数。 How do I get this context into my FailedPasswordHandler class? 如何将此上下文放入我的FailedPasswordHandler类中?

This is what I have in the MainActivity: 这是我在MainActivity中拥有的:

Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
ComponentName deviceAdmin = new ComponentName(MainActivity.this, FailedPasswordHandler.class);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin);
startActivityForResult(intent, 1);

And I want to create a CameraHandler object like this, in the FailedPasswordHandler class started by the intent above: 我想在由上述意图启动的FailedPasswordHandler类中创建这样的CameraHandler对象:

ch = new CameraHandler(this);
ch.initializeCamera();

The 'this' argument being the MainActivity. “ this”参数是MainActivity。

I like to handle this by using a custom Application class. 我喜欢通过使用自定义Application类来处理此问题。 For example: 例如:

public class Helper extends Application {

    private Context mContext;

    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    public Context getContext() {
        return mContext;
    }
}

This way you can get the context of the application every time you need it. 这样,您可以在每次需要时获取应用程序的上下文。

You can create a singleton application class with getContext function which will return application context. 您可以使用getContext函数创建一个单例应用程序类,该类将返回应用程序上下文。 But if you need an activity context, you can pass it as an argument to a constructor. 但是,如果需要活动上下文,可以将其作为参数传递给构造函数。

If you want to create a CameraHandler object in the same Activity, you can pass it like this : 如果要在同一Activity中创建CameraHandler对象,则可以像这样传递它:

ch = new CameraHandler(MainActivity.this);
ch.initializeCamera();

Else , you have to pass a parameter Context to your other class. 否则,您必须将参数Context传递给其他类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM