Jun*_*oor 1 multithreading android
场景是我有两个线程和一个UI线程.单击登录按钮时的UI线程创建一个ClientThread,它创建一个套接字并运行,直到套接字连接,每当收到一条消息我使用处理程序将消息发布到另一个名为ProcessDataThread的线程,现在接收来自服务器的一些消息我需要从ProcessDataThread更新UI相关的东西,我搜索了很多,我发现这两种方式runonUiThread函数我想只能从无用的活动类和Asynctask方法运行,我不知道如何将活动上下文传递给...
这是代码
单击MainActivity中的"登录按钮"时执行的代码
public void onLoginClick(View view)
{
global_constants.clientObject = new ClientThread();
global_constants.clientThread = new Thread(global_constants.clientObject);
global_constants.clientThread.start();
}
Run Code Online (Sandbox Code Playgroud)
ClientThread中的代码运行方法
public class ClientThread implements Runnable {
.......
@Override
public void run() {
......
while(!Thread.currentThread().isInterrupted() && (!CloseThread))
{
byte[] buff;
....
global_constants.updateConversationHandler.post(new ProcessDataThread(buff));
}
}
}
Run Code Online (Sandbox Code Playgroud)
解析出传入的数据和东西后,ProcessDataThread中的方法代码
public class ProcessDataThread implements Runnable {
.........
void ProcessLoginFailedPacket(byte[] buff)
{
// how to call the UI thread from here for updating some UI elements??
}
}
Run Code Online (Sandbox Code Playgroud)
[编辑]
我将活动上下文存储在一个全局变量中然后以这种方式进行,但我不知道它是否会更安全
((Activity)global_constants.MainContext).runOnUiThread(new Runnable(){
public void run()
{
TextView txtErr = (TextView) ((Activity)global_constants.MainContext).findViewById(R.id.errMsg);
txtErr.setVisibility(0);
txtErr.setText(reason);
}
});
Run Code Online (Sandbox Code Playgroud)
小智 7
您可以将运行UI操作的runnable发布到主线程,如下所示,
public class Utils {
public static void runOnUiThread(Runnable runnable){
final Handler UIHandler = new Handler(Looper.getMainLooper());
UIHandler .post(runnable);
}
}
Utils.runOnUiThread(new Runnable() {
@Override
public void run() {
// UI updation related code.
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5636 次 |
| 最近记录: |