2

I am new to kotlin, i am creating a framework to handle all my api call, the problem is that it doesn't have context. I would like to start an activity when i receive a certaine call of the api but i have no activity so i can't Intent. What i have tried :

val intent = Intent(this, testActivity::class.java)
startActivity(intent)

But it's that that i need context. I also tried to create a global Class Application with a companion object context but i get an error Required Context found Intent.

val intent = Intent(App.context, testActivity::class.java)
startActivity(intent)

Is there a way to start an activity in a class ? or what should i do ?

XCarb
  • 735
  • 10
  • 31

2 Answers2

1

Create Application class and create instance.

@Synchronized
        fun getInstance(): MyApplication ? {
            return mInstance
    }

Initialize in Application's onCreate() method

override fun onCreate() {
        super.onCreate()
        mInstance = this
    }

Now use instance as your context in your whole app

MyApplication.getInstance()
Komal
  • 328
  • 3
  • 15
0

From your activity, pass applicationContext as a parameter to your API class when creating an instance of the API class. You can do this via constructor injection. You can then use the received applicationContext to start activities and services

Rafsanjani
  • 4,352
  • 1
  • 14
  • 21