我怎么能发送消息给处理器从静态函数? [英] How can i send message to handler from a static function?
问题描述
我知道,这又是一个重复的问题,但我的情况是不同的问题。
I know, this is again a repeated question but my case it is different question.
我有一个ABC类的静态功能和安培;处理程序。早些时候,我不能从一个静态函数可以调用句柄。然后,我用Google搜索从静态函数访问非静态函数&放大器;找到了一个解决方案是创建类和放大器的一个实例;访问非静态变量。但现在,为什么,我为得到这个错误。
I have a class abc with a static function & a Handler. Earlier i couldn't able call handler from a static function. Then i googled for Access a non-static function from a static function & found an solution is to create an instance of class & access non-static variable. But now, why, i m getting this error.
E / AndroidRuntime(13343):java.lang.RuntimeException的:内螺纹尚未调用无法建立处理活套prepare()
E/AndroidRuntime(13343): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
public class abc
{
static public void Instantiate()
{
abc xyz = new abc();
xyz.handler.sendEmptyMessage(1); **//GETTING ERROR IN THIS LINE**
}
public Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
}
}
}
}
我的提问:我怎么能发送消息给的处理的从一个静态函数
My Question: How can i send message to handler from a static function?
Thankx。
推荐答案
检查,你这样做是对的地方:
check the place where you are doing this:
abc.Instantiate();
和它替换为
runOnUiThread(new Runnable() {
@Override
public void run() {
abc.Instantiate();
}
});
我希望你从一个活动调用它
I hope you're calling it from an Activity
一些解释(的 引用的 bicska88):)的
Some Explanation (quoting bicska88) :)
是什么原因导致的问题,并没有什么关系,你从一个静态函数将消息发送到处理程序
对象的事实。问题是,你还没有被称为一个线程发送消息给处理活套。prepare()
(如错误消息说,该线程没有按'吨有一个 消息循环
)。这可能是固定的通过显式调用活套。prepare()
之前,同时,或通过运行在UIThread的code。
What causes the problem, doesn't have anything to do with the fact that you send a message to a Handler
object from within a static function. The problem is that you send a message to the handler from a thread that has not called Looper.prepare()
(as the error message says, the thread doesn't have a message loop
). This may be fixed by explicitly calling Looper.prepare()
before-while, or by running the code on the UIThread.
这篇关于我怎么能发送消息给处理器从静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!