gpt4 book ai didi

android - 如何在 do while 情况下使用 UI 线程处理 AsyncTask

转载 作者:行者123 更新时间:2023-11-30 02:43:25 26 4
gpt4 key购买 nike

我正在用 android 编写一个套接字客户端应用程序。现在我遇到了如何在 do while 循环中处理嵌套 UI 的问题。因为我希望我的程序一直监听来自服务器的消息,直到服务器终止。因为网络异常,我把那些socket连接放到了AsyncTask中,但是一旦我运行客户端,它只能处理processConnection()中的readobject()

这是原始客户端代码。

package com.example.socketclien;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.OutputStream;
import java.io.StreamCorruptedException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ClientFragment extends Fragment {

private Socket clientSocket;
private Button mSentButton;
private TextView mMessageTextView;
private EditText mMessagEditText;
private String message="";
private ObjectOutputStream outputStream;
private ObjectInputStream inputStream;
private static String TAG="clientFragment";
AsyncTask<Void, Void, Void> mRegisterTask;

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.i(TAG,"onCreate starts");

}
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
//refer a view which wires a layout
View v = inflater.inflate(R.layout.fragment_client,parent,false);

mSentButton=(Button)v.findViewById(R.id.Sentbutton);
mMessageTextView=(TextView)v.findViewById(R.id.messageTextView);
Log.i(TAG,"onCreateView starts");
mMessagEditText=(EditText)v.findViewById(R.id.Message);
new connection().execute();

return v;
}

public void runClient() throws IOException, Throwable
{
Log.i(TAG,"runClient() starts");
connectToServer();
getStreams();
processConnection();
closeConnection();
}




private void connectToServer() throws IOException, Exception {
// TODO Auto-generated method stub
Log.i(TAG,"connectToServer() starts");
mMessageTextView.setText("Attempting connection\n");
Log.i(TAG,"connectToServer() 's setText starts");
clientSocket = new Socket("134.129.125.123",8080);
Log.i(TAG,"connectToServer() 's Connect to 134.129.125.123");
mMessageTextView.append("Connect to "+"134.129.125.123 \n");
}


private void getStreams() throws IOException{
// TODO Auto-generated method stub
Log.i(TAG,"getStreams()'s onGetStream starts");
outputStream = new ObjectOutputStream(clientSocket.getOutputStream());
outputStream.flush();
Log.i(TAG,"getStreams()'s outputStream created");
inputStream = new ObjectInputStream(clientSocket.getInputStream());
mMessageTextView.append("\nGot i/O stream \n");

}

private class connection extends AsyncTask{

@Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
try {
connectToServer();
getStreams();
processConnection();
closeConnection();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}



}
private void processConnection(){

Log.i(TAG,"ProcessConnection() starts");
// TODO Auto-generated method stub
do {


try {
message=(String) inputStream.readObject();
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(TAG,"ProcessConnection()'s readobject() starts");

mMessageTextView.append("\n"+ message);
Log.i(TAG,"ProcessConnection()'s append() starts");


} while (!message.equals("SERVER>>> TERMINATE"));
}


private void closeConnection() throws IOException {
// TODO Auto-generated method stub
Log.i(TAG,"closeConnection starts");
mMessageTextView.append("\nTerminating connection\n");

outputStream.close();
inputStream.close();
clientSocket.close();
}

private void sentDate(String message)
{
try {
outputStream.writeObject("CLIENT>>>"+message);
outputStream.flush();
mMessageTextView.append("\nCLIENT>>>"+ message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

错误:

08-22 11:11:53.230: W/System.err(12048): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
08-22 11:11:53.240: W/System.err(12048): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6024)
08-22 11:11:53.240: W/System.err(12048): at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:853)
08-22 11:11:53.240: W/System.err(12048): at android.view.ViewGroup.invalidateChild(ViewGroup.java:4320)
08-22 11:11:53.240: W/System.err(12048): at android.view.View.invalidate(View.java:10935)
08-22 11:11:53.240: W/System.err(12048): at android.view.View.invalidate(View.java:10890)
08-22 11:11:53.240: W/System.err(12048): at android.widget.TextView.updateAfterEdit(TextView.java:7430)
08-22 11:11:53.240: W/System.err(12048): at android.widget.TextView.handleTextChanged(TextView.java:7453)
08-22 11:11:53.240: W/System.err(12048): at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:9187)
08-22 11:11:53.240: W/System.err(12048): at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:962)
08-22 11:11:53.240: W/System.err(12048): at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:496)
08-22 11:11:53.240: W/System.err(12048): at android.text.SpannableStringBuilder.append(SpannableStringBuilder.java:253)
08-22 11:11:53.240: W/System.err(12048): at android.text.SpannableStringBuilder.append(SpannableStringBuilder.java:30)
08-22 11:11:53.240: W/System.err(12048): at android.widget.TextView.append(TextView.java:3409)
08-22 11:11:53.240: W/System.err(12048): at android.widget.TextView.append(TextView.java:3396)
08-22 11:11:53.240: W/System.err(12048): at com.example.socketclien.ClientFragment.processConnection(ClientFragment.java:174)
08-22 11:11:53.240: W/System.err(12048): at com.example.socketclien.ClientFragment.access$2(ClientFragment.java:153)
08-22 11:11:53.240: W/System.err(12048): at com.example.socketclien.ClientFragment$connection.doInBackground(ClientFragment.java:100)
08-22 11:11:53.240: W/System.err(12048): at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-22 11:11:53.240: W/System.err(12048): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-22 11:11:53.240: W/System.err(12048): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-22 11:11:53.240: W/System.err(12048): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-22 11:11:53.240: W/System.err(12048): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-22 11:11:53.240: W/System.err(12048): at java.lang.Thread.run(Thread.java:841)
08-22 11:15:51.574: W/System.err(13286): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
08-22 11:15:51.574: W/System.err(13286): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6024)
08-22 11:15:51.574: W/System.err(13286): at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:853)
08-22 11:15:51.574: W/System.err(13286): at android.view.ViewGroup.invalidateChild(ViewGroup.java:4320)
08-22 11:15:51.574: W/System.err(13286): at android.view.View.invalidate(View.java:10935)
08-22 11:15:51.574: W/System.err(13286): at android.view.View.invalidate(View.java:10890)
08-22 11:15:51.574: W/System.err(13286): at android.widget.TextView.updateAfterEdit(TextView.java:7430)
08-22 11:15:51.584: W/System.err(13286): at android.widget.TextView.handleTextChanged(TextView.java:7453)
08-22 11:15:51.584: W/System.err(13286): at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:9187)
08-22 11:15:51.584: W/System.err(13286): at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:962)
08-22 11:15:51.584: W/System.err(13286): at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:496)
08-22 11:15:51.584: W/System.err(13286): at android.text.SpannableStringBuilder.append(SpannableStringBuilder.java:253)
08-22 11:15:51.584: W/System.err(13286): at android.text.SpannableStringBuilder.append(SpannableStringBuilder.java:30)
08-22 11:15:51.584: W/System.err(13286): at android.widget.TextView.append(TextView.java:3409)
08-22 11:15:51.584: W/System.err(13286): at android.widget.TextView.append(TextView.java:3396)
08-22 11:15:51.584: W/System.err(13286): at com.example.socketclien.ClientFragment.processConnection(ClientFragment.java:131)
08-22 11:15:51.584: W/System.err(13286): at com.example.socketclien.ClientFragment.access$2(ClientFragment.java:110)
08-22 11:15:51.584: W/System.err(13286): at com.example.socketclien.ClientFragment$connection.doInBackground(ClientFragment.java:98)
08-22 11:15:51.584: W/System.err(13286): at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-22 11:15:51.584: W/System.err(13286): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-22 11:15:51.584: W/System.err(13286): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-22 11:15:51.584: W/System.err(13286): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-22 11:15:51.584: W/System.err(13286): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-22 11:15:51.584: W/System.err(13286): at java.lang.Thread.run(Thread.java:841)

我知道这一定发生在 UIthread 和 Asytask 之间。

最佳答案

您不能从非 UI 线程更新 UI 线程或任何小部件。 asynctask 是一个非 UI 线程,所以你不能从它的方法中更新你的 textview 你在 onPreExecute()onProgressUpdateonPostExecute() 。每次你想访问 UI 线程时,你可以使用 runOnUiThread 例如,doInBackground 方法中的所有异步任务代码都可以访问 mMessageTextView 喜欢以下任何一种方式:

 ClientFragment.this.getActivity().runOnUiThread(new Runnable() {

@Override
public void run() {
mMessageTextView.append("\nTerminating connection\n");
}
});

或者你可以使用:

   mMessageTextView.post(new Runnable() {

@Override
public void run() {
mMessageTextView.append("\nTerminating connection\n");
}
});

您还可以使用 publishProgress()onProgressUpdate 发布您的更新。有关快速信息,请查看:

http://developer.android.com/reference/android/os/AsyncTask.html

你也可以使用handler。如果您想了解更多,请让我编辑此答案以包含处理程序示例代码。

关于android - 如何在 do while 情况下使用 UI 线程处理 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25451577/

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