Arthelais
Arthelais

Reputation: 646

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.

Upvotes: 0

Views: 75

Answers (3)

Alessandro Roaro
Alessandro Roaro

Reputation: 4733

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.

Upvotes: 1

ahmed_khan_89
ahmed_khan_89

Reputation: 2773

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.

Upvotes: 0

smb
smb

Reputation: 834

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.

Upvotes: 0

Related Questions