[英]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) object
为Android 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.