java - 无法从 AsyncTask 和无限循环更新 EditText

标签 java android sockets loops android-asynctask

我有以下问题。在主线程上,我有一个 EditText 字段,我有一个 AsyncTask,它无限地监听传入消息的套接字。在循环中(位于 doInBackground())我试图调用 onProgressUpdate() 并向它传递一个字符串,我希望 oPU() 收到string 以将其显示在位于主线程的 EditText 上。

  public class ClientSide extends AsyncTask<String, String, String>{
  public EditText field = (EditText) findViewById(R.id.bar1);
  ...}

第一个问题是 findViewById(R.id.bar1) 它说无法解析符号。可能是什么原因造成的,我该如何解决。 第二个问题是循环。问题是我不想通过主线程定期创建新的 AsyncTask 对象,因为在我的例子中,这意味着创建一个套接字并在每次对象为 .execute() 时绑定(bind)到它 -编辑。请建议我一种重新组织代码的方法,以便使该解决方案更加优雅。我知道 AsyncTasks 适用于短流程而不是应用程序长流程,所以我知道我当前的解决方案(带循环)是一个分解的胡萝卜(又名坏胡萝卜)。 再次: 1. 如何让findViewById()真正匹配EditText UI元素? 2. 如何重新组织我的代码,以便在应用需要在后台执行其消息监听器时不每次都创建套接字?

您也可以看到 Async.. doInBackground:

protected String doInBackground(String... params){

    final String SERVER_HOSTNAME = "hereGoesMyIP";
    final int SERVER_PORT = 2002;
    BufferedReader mSocketReader;
    PrintWriter mSocketWriter;
    final String TAG = ClientSide.class.getSimpleName();
    String outputln = "Me. Android";


    try {
        //Initialization of the socket, socket reader and writer.
        Socket socket = new Socket(SERVER_HOSTNAME, SERVER_PORT);
        mSocketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        mSocketWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        System.out.println("Connected to server " + SERVER_HOSTNAME + ":" + SERVER_PORT);


        //An infinite loop which checks for incoming messages.
        while(true){
            String inMsg="";
            String aMessage = "";

            //Reads from the socket
            if((inMsg=mSocketReader.readLine())!=null && socket.isConnected()){
                publishProgress(inMsg);
            }

            Thread.sleep(500);//still requres try - catch?
        }


    } catch (IOException ioe) {
        System.err.println("Cannot connect to " + SERVER_HOSTNAME + ":" + SERVER_PORT);
        ioe.printStackTrace();

    }

    return null;
}

最佳答案

1)findViewByid() 是 Activity 类中可用的方法。它在 AsyncTask 类中不可用。所以像这样将你的 View 传递给 AsyncTask

 private Context mContext;
private View yourView;


    public Clientside(Context context, View rootView){
        this.mContext=context;
        this.yourView=rootView;
    }

然后就可以这样访问了

EditText editText = yourView.findViewById(R.id.edit_text);

请记住,您无法从后台线程更新 View ,因此请使用 progressupdate()postExecute() 方法来更新在主线程上运行的 EditText。

@Override
protected void onPostExecute(String result) {

}


  View rootView = findViewById(android.R.id.content).getRootView();//This will return you the rootView



ClientSide cs = new ClientSide(getApplicationContext(),rootView);//do this in your mainactivity

getApplicationContext() 将返回您所在的上下文。

谢谢。我希望这对您有所帮助。

关于java - 无法从 AsyncTask 和无限循环更新 EditText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36245592/

相关文章:

java - 从 JAR 读取/写入 .txt 文件

android - 从字符串值文件夹获取字符串数组?

android - 当锁定屏幕中屏幕方向发生变化时,如何防止我的 Android 应用程序崩溃?

python - ZeroMQ 无法在 [0.0.0.0 :5555] - address already in use. 上的 Docker 上进行 .bind() 为什么?

明确绑定(bind)()套接字函数

java - 尝试使用 ResourceBundle 从外部文件中获取消息

java - 摄像头输入 : Unsupported Parameter

java - 在java中为selenium设置firefox和chrome驱动程序?

android - TextView和其他TextView挤压时的Ellipsize

javascript - 写入套接字非常快会导致连接缓冲区