简体   繁体   中英

Need context in non-activity

I have a MainActivity, a class called FailedPasswordHandler and a CameraHandler. The FailedPasswordHandler implements the DeviceAdminReceiver. Now I want to create a CameraHandler object in the FailedPasswordHandler class, but it requires a context argument. How do I get this context into my FailedPasswordHandler class?

This is what I have in the 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:

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

The 'this' argument being the MainActivity.

I like to handle this by using a custom Application class. 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. 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 :

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

Else , you have to pass a parameter Context to your other class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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