发布处理程序时显示敬酒

时间:2018-08-07 14:12:08

标签: android kotlin

我已经尝试了thisgetApplicationContext()的每个上下文,但是没有用。

 class MyServerThread : Runnable {
    internal lateinit var s: Socket
    internal lateinit var ss: ServerSocket
    internal lateinit var isr: InputStreamReader
    internal lateinit var bf: BufferedReader
    internal lateinit var message: String
    internal var h = Handler()


    override fun run() {
        try {
            ss = ServerSocket(3050)
            while (true) {
                s = ss.accept()
                isr = InputStreamReader(s.getInputStream())
                bf = BufferedReader(isr)
                message = bf.readLine()
                h.post {
                    Toast.makeText(this, message, Toast.LENGTH_LONG).show()

                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}

我该如何解决该问题?

3 个答案:

答案 0 :(得分:1)

解决方案:尝试使用此代码

class MyServerThread(val context: Context) : Runnable {
    internal lateinit var s: Socket
    internal lateinit var ss: ServerSocket
    internal lateinit var isr: InputStreamReader
    internal lateinit var bf: BufferedReader
    internal lateinit var message: String
    internal var h = Handler()


    override fun run() {
        try {
            ss = ServerSocket(3050)
            while (true) {
                s = ss.accept()
                isr = InputStreamReader(s.getInputStream())
                bf = BufferedReader(isr)
                message = bf.readLine()
                h.post {
                    Toast.makeText(context, message, Toast.LENGTH_LONG).show()
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}

答案 1 :(得分:0)

this是可运行对象,而不是上下文对象。而且Runnable没有getApplicationContext方法

您必须在此类中添加一个接受有效Context的构造函数,您可以将其传递给Toast

答案 2 :(得分:0)

只需在Runnable中添加构造函数

Context context;
public MyServerThread(Context context) {
    this.context=context;
 }

在活动内部(用于传递上下文)

MyServerThread name=new MyServerThread(getBaseContext());

然后最后在烤面包中传递上下文:

Toast.makeText(context,message,Toast.LENGTH_LONG).show();