我正在开发一种软件,其中PC和移动设备与服务器通信。当我从JAVA桌面应用程序运行代码时,它给我以下错误
android.os.NetworkOnMainThreadException
我试图将我的类作为一个线程实现,但我认为我没有把它弄好。它仍然给我错误
我很乐意得到任何支持。
ServerAccessMobile类正在执行所有网络,并且有两个公共方法,一个用于从服务器获取数据,另一个用于在服务器上设置数据
这就是我想从任何Activity / Service
执行它的方式ServerAccessMobile serverAccessMobile = new ServerAccessMobile();
ArrayList <String> dataFromServer = **serverAccessMobile.getDataFromServer()**;
ArrayList <String> dataToSend = .....
**serverAccessMobile.setDataOServer(dataToSend)**;
这是ServerAccessMobile类的代码
public class ServerAccessMobile {
// private variables
private ObjectOutputStream outputStream;
private ObjectInputStream inputStream;
...
// constructor
public ServerAccessMobile(String arg1)
{
...
}
**private ArrayList<String> run(ArrayList<String> messageToSendList)**
{
ArrayList <String> receivedMessageList = new ArrayList <String> ();
try // connect to server, get streams, process connection
{
connectToServer(); // create a Socket to make connection
getStreams(); // get the input and output streams
sendData(messageToSendList);
receivedMessageList = processConnection();
}
catch ( EOFException eofException )
{
System.out.println("\n terminated connection");
}
catch ( IOException ioException )
{
ioException.printStackTrace();
}
finally
{
closeConnection(); // close connection
}
return receivedMessageList;
}
public ArrayList <String > getDataFromServer(){
ArrayList< String > commandMessage = new ArrayList< String > ();
commandMessage.add("GETDATA");
ArrayList< String > receivedMessageList = new ArrayList< String > ();
// start server communication
receivedMessageList = **run(commandMessage);**
}
public void setDataOnServer(ArrayList <String> messageToSendList){
// start server communication
**run(messageToSendList);**
}
}
现在我的问题,
run()方法中的代码应该在单独的线程中运行,而不是ui线程 我该如何正确实施呢?
谢谢你
答案 0 :(得分:1)
您可以在以下链接中找到有关线程的详细说明:http://developer.android.com/guide/components/processes-and-threads.html#Threads
你可以做这样的事情
$_SERVER['SERVER_NAME']
如果要从此线程更新UI,则必须调用view.post(Runnable)方法。