1

我在按钮中有一个进程(大进程)。我想用不同的值更新 TextView。像:

  • 正在连接...
  • 接收文件...
  • 完全的...

ETC..

我正在使用 setText(); void,但我只得到 setText(); 的最后一个值,在这种情况下:

estatEdit.setText("Tareas completadas!");

这是我的代码...

public class sincroGeneral extends Activity implements OnClickListener { 
    private static final String CATEGORIA = "libro"; 
    private static final String HOST = "192.168.1.165"; 
    private static final int PORT = 9889; 
    private static final int PORTDATOS = 9888;

    int filesize=6022386;
    int bytesRead;
    int current = 0;

    byte [] mybytearray  = new byte [filesize];

    byte buffer[] = new byte[1024];
    byte buffer2[] = new byte[1024];
    byte bufferArxiu[] = new byte[2048];
    int s;
    int s2;
    String Benvinguda; 
    String compra;
    EditText estatEdit;
    EditText editInflated;

    File myfile;

    SQLiteDatabase baseDatos;
    LinearLayout mainLayout;
    View view2;

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle bundle) { 
        super.onCreate(bundle); 
        setContentView(R.layout.sincrolayout); 



        Button b = (Button) findViewById(R.id.BotoEnviarSincro); 
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                Button b = (Button) findViewById(R.id.BotoEnviarSincro);
                estatEdit = (EditText) findViewById(R.id.editSincro);

                estatEdit.setText("Enviando petición...");



                b.setClickable(false);
                b.setFocusable(false);
                b.setEnabled(false);


                ProcesRebre();

                b.setClickable(true);
                b.setFocusable(true);
                b.setEnabled(true);
            }
            });  
    }




    private void mostrarMensaje(String mensaje)
    {
        Toast.makeText(this, mensaje, 500).show();
    }


    private void ProcesRebre()
    {
        Socket sockDatos = null; 
        Socket clientSocket = null;



        DataOutputStream sortida;
        DataInputStream entrada;
        BufferedReader inFromServer;


        DataOutputStream sortidaDatos;
        DataInputStream entradaDatos;
        BufferedReader inFromServerDatos;






        try { 
            estatEdit.setText("Conectando...");

            clientSocket = new Socket(HOST, PORT);




            sortida = new DataOutputStream(clientSocket.getOutputStream());
            entrada = new DataInputStream(clientSocket.getInputStream());
            inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));




            sortida.writeBytes("FAS4-F@S-1-F@S- 1.0.152-F@S-");

            Log.i("Enviat","OK");

            clientSocket.setSoTimeout(30000);

            s =  entrada.read(buffer);
            String str = new String(buffer, "UTF8");


            clientSocket.setSoTimeout(0);


            Log.i("Rebut","OK");

           if(str.contains("PDA1-F@S-"))
           {
                sockDatos = new Socket(HOST, PORTDATOS);

               estatEdit.setText("Esperando archivo....");
                sortidaDatos = new DataOutputStream(sockDatos.getOutputStream());
                entradaDatos = new DataInputStream(sockDatos.getInputStream());
                inFromServerDatos = new BufferedReader(new InputStreamReader(sockDatos.getInputStream()));



                sortidaDatos.writeBytes("FAS4-F@S-1-F@S- 1.0.150-F@S-");


                if(sockDatos.isConnected())
                {
                     System.out.println("Conectat amb port 9888");
                }

                File carpetaSincro = new File(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/");
                carpetaSincro.mkdirs();

                File ArxiuSincro = new File (Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip");

                if(ArxiuSincro.exists())
                {
                    ArxiuSincro.delete();
                }

                File ArxiuSincro2 = new File (Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip");
                ArxiuSincro2.createNewFile();


                sortida.writeBytes("FAS2-F@S-");

                String str2= "";



                clientSocket.setSoTimeout(30000);


                while(true && (!str2.contains("PDA7-F@S-") && !str2.contains("PDAERR1-F@S-")))
                    {
                        s2 = entrada.read(buffer2);  

                        str2 = new String(buffer2, "UTF8");

                    }

                clientSocket.setSoTimeout(0);

                String replace1 = str2.replace("PDA7-F@S-", "");
                String replace2 = replace1.replace(" ", "");
                String tamanyArxiu = replace2.replace("-F@S-ZIP","");


                int bufferZip = Integer.parseInt(tamanyArxiu);

                boolean in;
                s2 = 0;
                sockDatos.setSoTimeout(30000);
                RandomAccessFile archivo = new RandomAccessFile(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip", "rw");
                long tamArxActual = 0;

                    while(bufferZip>=tamArxActual)
                    {
                        sockDatos.setSoTimeout(10000);
                        s2 = entradaDatos.read(bufferArxiu);
                        estatEdit.setText("Recibiendo archivo....");
                        archivo.write(bufferArxiu);

                        tamArxActual = archivo.length();

                        Thread.sleep(2);
                    }

                    sockDatos.setSoTimeout(0);

                    estatEdit.setText("Archivo recibido");

                    str2 = "";

                    clientSocket.setSoTimeout(30000);

                    while(true && (!str2.contains("PDA3-F@S-") && !str2.contains("PDAERR1-F@S-")))
                    {
                        s2 = entrada.read(buffer2);  

                        str2 = new String(buffer2, "UTF8");

                    }

                    clientSocket.setSoTimeout(0);

                    if(str2.contains("PDA3-F@S-"))
                    {
                        sortida.writeBytes("FAS7-F@S-");
                        Thread.sleep(2000);

                        sortida.writeBytes("FAS6-F@S-");
                    }




                    sockDatos.close();
                    clientSocket.close();


                    String pathZip = Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip";
                    String directoriExtraccio = Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/";
                    String pathTxt = Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt";
                    UnzipUtility unzipper = new UnzipUtility();

                    try {
                        unzipper.unzip(pathZip, directoriExtraccio);
                    } catch (Exception ex) {
                        System.out.print("No s'ha pogut descomprimir l'arxiu");
                        ex.printStackTrace();
                    }

                    File f = new File(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.dll");
                    f.renameTo(new File(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt"));


                    importarSincro();





           }


        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }




    private void importarSincro() throws SQLException, IOException
    {

        int contador = 0;
        String LiniaSQL;


        FileInputStream fstream = new FileInputStream(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt");
        DataInputStream DataInFile = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(
                new InputStreamReader(new FileInputStream(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt"), "Latin-1"));

        String FinalSQL = "";

        baseDatos = openOrCreateDatabase("BBDD", MODE_WORLD_WRITEABLE, null);

        baseDatos.execSQL("BEGIN");
        while ((LiniaSQL = br.readLine()) != null)   {



            if(contador > 0)
            {
                FinalSQL = LiniaSQL.replace("***** ", "");
                if(FinalSQL.contains("DELETE") && !FinalSQL.contains("DELETE FROM"))
                {
                    FinalSQL = FinalSQL.replace("DELETE", "DELETE FROM");

                    try{
                        baseDatos.execSQL(FinalSQL);
                    }catch(SQLiteException e){


                    }
                }
                else
                {
                    try{
                        baseDatos.execSQL(FinalSQL);
                    }catch(SQLiteException e){


                    }
                }






                LiniaSQL = "";
            }

            contador++;

        }
        baseDatos.execSQL("COMMIT");
        estatEdit.setText("Tareas completadas!");
        baseDatos.close();



    }


    /////////////////////////////////////////


    public static String deserializeString(File file)
              throws IOException {
                  int len;
                  char[] chr = new char[4096];
                  final StringBuffer buffer = new StringBuffer();
                  final FileReader reader = new FileReader(file);
                  try {
                      while ((len = reader.read(chr)) > 0) {
                          buffer.append(chr, 0, len);
                      }
                  } finally {
                      reader.close();
                  }
                  return buffer.toString();
              }




    public void onClick(View arg0) {
        // TODO Auto-generated method stub

    }

}

提前致谢!

大卫。

4

3 回答 3

0

Internet 连接是一个阻塞操作,即它会阻塞 UI,直到操作完成(这就是为什么只看到最后一次更新的原因)。您必须将其移至线程(甚至更好地移至 AsyncTask)。但是你会遇到另一个问题,你不能从主线程之外更新 UI。因此,您必须使用 Handler 来更新 UI。

于 2012-09-24T08:43:00.653 回答
0

您正在主线程上执行网络操作,这里要理解的是 Android 在单个主线程上运行,所以如果您对服务/活动/内容提供程序等进行任何耗时的操作,它将阻塞您的主线程,因此所有的东西都会看起来它们被阻止/无响应,实际上您将在几秒钟后收到 ANR 消息。

最后,遵循这种方法

  1. 将您的网络扩展代码移动到单独的线程
  2. 实现消息处理机制以在主线程 (Handler/Looper) 上更新您的 UI

为了进一步帮助解决问题,Android 为此目的为您提供了一个 AsynTask 类。您可以在 doInBackground() 中进行操作,并且在条件下您可以通过 onProcessUpdate() 更新您的 UI

希望这可以帮助。

于 2012-09-24T08:53:42.503 回答
0

如果您在 UI 线程上运行此过程,可能会导致提示“应用程序
未响应”的对话框。因此我建议必须在AsyncTask或 Service中完成此任务

你可以更新你的文本视图

onPreExecute()
onProgressUpdate()
onPostExecute() functions in AsyncTask.

例如下载文件

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
于 2012-09-24T08:54:04.867 回答