我在android服务中的主线程(UI thraed)中编写了一个方法。在这个方法中,我创建了一个处理程序类,如下所示
public void myMethod(){
public Handler _handler = new Handler(){
public void handleMessage(Message msg){
Log.v("LOG_TAG", "value of msg===>"+msg);
}
};
我的问题是如何在另一个线程中调用_handler对象,以便我可以将数据传递给处理程序类。
谢谢
答案 0 :(得分:0)
尝试,
public void myMethod(){
Handler _handler = new Handler(Looper.getMainLooper()){
public void handleMessage(Message msg){
// Call your method of UI thread here... it will work.
Toast.makeText(context, "UI test", Toast.LENGHT_SHORT).show();
Log.v("LOG_TAG", "value of msg===>"+msg);
}
};
_handler.sendEmptyMessage(0);
}
还有一个替代方案:
public void myMethod(){
Handler _handler = new Handler(Looper.getMainLooper());
_handler.post(new Runnable() {
// Call your method of UI thread here... it will work.
Toast.makeText(context, "UI test", Toast.LENGHT_SHORT).show();
});
}
如果您无法在myMethod(不在范围内)调用您的ui方法,请参阅: https://stackoverflow.com/a/14444110/3582473