Kotlin是否可以从课堂开始一项活动? [英] Kotlin is it possible to start an activity from a class?

查看:62
本文介绍了Kotlin是否可以从课堂开始一项活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Kotlin的新手,我正在创建一个处理所有api调用的框架,问题是它没有上下文.当我收到api的确定调用时,我想开始一项活动,但是我没有任何活动,因此我无法进行Intent. 我尝试过的:

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)

但这就是我需要上下文. 我还尝试用伴侣对象上下文创建一个全局类应用程序,但是却收到一个错误,发现所需的上下文是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 ?

推荐答案

创建应用程序类并创建实例.

Create Application class and create instance.

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

在应用程序的onCreate()方法中初始化

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()

这篇关于Kotlin是否可以从课堂开始一项活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆