简体   繁体   English

无法在可运行线程内解析上下文

[英]Context not resolved inside a runnable thread

Here is the code inside main Activity class, which works fine.. 这是Activity类中的代码,可以正常工作。

public void onStart() {
    super.onStart();

mHandler = new Handler();
    context = this;
    ...
}

And the following code gives problem, don't know why: 而以下代码给了问题,不知道为什么:

public void onStart() {
    super.onStart();

    new Thread(new Runnable(){
            public void run(){
            mHandler = new Handler();
            context = this;
            ...
        }
    }).start();
}
new Thread(new Runnable(){
            public void run(){
            mHandler = new Handler();
            context = this;
            ...
        }
    }).start();

In above code .this refers to Thread (Runnable) class object not a Current Activity . 在上面的代码中.this是指Thread (Runnable)类对象,而不是Current Activity And you can not cast Thread (Runnable) object to Android Context . 而且您不能将Thread (Runnable) objectAndroid Context

or something like, 或类似的东西,

context = <MainActivity>.this 

Replace context = this; 替换context = this; with context = MainActivity.this as it is referencing the Thread object not the MainActivity object. with context = MainActivity.this因为它引用Thread对象而不是MainActivity对象。

this refers to the Runnable instance. this是指Runnable实例。 You want the enclosing activity so use MyActivityClass.this instead. 您需要封闭活动,因此请使用MyActivityClass.this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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