gpt4 book ai didi

java - Android 多线程

转载 作者:行者123 更新时间:2023-12-01 04:20:30 25 4
gpt4 key购买 nike

我正在尝试制作一个连接到服务器的 Android 应用程序(通过 Socket),并且我相信我需要在不同的线程中执行此操作。但是,显然,我无法从另一个线程访问或修改 Android UI。我该怎么办?

package me.nrubin29.quiz.student;

import android.app.Activity;
import android.widget.Toast;

import java.io.EOFException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Connection {

private Socket socket;
private Thread reader;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;

public void initConnection(final Activity activity, final String ip, final String port, final String name) {
new Thread(new Runnable() {
public void run() {
try {
Toast.makeText(activity.getApplicationContext(), "Starting connection to " + ip + ":" + Integer.parseInt(port), Toast.LENGTH_SHORT).show();

socket = new Socket(ip, Integer.parseInt(port));

Toast.makeText(activity.getApplicationContext(), "Connected!", Toast.LENGTH_SHORT).show();

outputStream = new ObjectOutputStream(socket.getOutputStream());

inputStream = new ObjectInputStream(socket.getInputStream());

outputStream.writeObject(name);

reader = new Thread(new Runnable() {
public void run() {
while (true) {
try {
Object in = inputStream.readObject();
System.out.println(in);
}
catch (EOFException e) { Toast.makeText(activity.getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); }
catch (Exception e) { e.printStackTrace(); }
}
}
});

reader.start();
}
catch (Exception e) { e.printStackTrace(); }
}
}).start();
}
}

最佳答案

您可以使用runOnUiThread

activity.runOnUiThread(new Runnable() //run on ui thread
{
@Override
public void run()
{
// update ui
}
});

http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)

public final void runOnUiThread (Runnable action)

Added in API level 1
Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

Parameters
action the action to run on the UI thread

关于java - Android 多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18967353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com