0

我想在我的活动中显示一个进度条,其中包含使用套接字测试服务器连接的代码。我希望我的进度条仅在向服务器发送数据时可见。一旦我收到服务器的回复,进度应该被取消并显示带有消息“服务器忙”的警报框。但在我的屏幕上,从服务器获得回复后进度条可见。这是我的代码。

 public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            mProgress = (ProgressBar) findViewById(R.id.progressBar1);
            mProgress.setProgress(0);
            checkdb();
        }
    private void checkdb() {        
            String message = "";
            try {

                serverIpAddress = InetAddress.getByName("192.168.1.133");

                Log.d("TCP", "C: Connecting...");
                socketObject = new Socket(serverIpAddress, 8221);
                String str = "hi";
                try {
                    Log.d("TCP", "C: Sending: '" + str + "'");
                    PrintWriter out = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(socketObject.getOutputStream())), true);
                    out.println(str);

                    inputStream = socketObject.getInputStream();

                    inputDataStream = new DataInputStream(inputStream);

                    message = inputDataStream.readUTF();
                    Log.d("TCP", "C: Reply: '" + message + "'");
                } 
                catch(IOException e)
                {

                    Log.e("TCP", "S: Error", e);
                }catch (Exception e) {

                    Log.e("TCP", "S: Error", e);
                }

                finally {

                    socketObject.close();
                    Log.e("TCP", "S: Error");
                }

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                Log.e("TCP", "C: UnknownHostException", e);
                e.printStackTrace();
            } 
            catch(IOException e)
            {

                Log.e("TCP", "S: Error:", e);

             //Code to show Alert box with message "IOException"

            }
        }

所以在我从服务器得到回复之前应该怎么做才能让我的进度条可见。如果我得到回复,进度条应该被关闭。任何人请帮助我...

4

3 回答 3

2

这是我在使用 AsyncTask 对用户进行身份验证时实现进度条的方式。看看这是否可以帮助你

        private class LoginTask extends AsyncTask<String, Integer, Boolean>{
    private final ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
    public LoginTask(LoginActivity activity) {   

    } 

    @Override 
    protected void onPreExecute() { 
        this.dialog.setMessage("Please wait.."); 
        this.dialog.setIndeterminate(true) ;
        this.dialog.setCancelable(false);
        this.dialog.show();  
        } 


    @Override
    protected Boolean doInBackground(String... params) {
        try {
            Thread.sleep(5000); //Execute long running task
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    @Override
    protected void onPostExecute(Boolean result) { 
        if (this.dialog.isShowing()) {            this.dialog.dismiss();         }
        LoginActivity.this.processAuthenticationResult(result.booleanValue());
    }

}   

并从我的 LoginActivity 中调用它,如下所示

 new LoginTask(LoginActivity.this).execute(new String[]{userName, password});
于 2011-12-29T07:46:09.013 回答
0

只需使用mProgress.setVisibility(View.GONE)mProgress.setVisibility(View.VISIBLE)隐藏和显示您的小部件。

为避免您的主要用户活动被阻塞,您需要在单独的线程中执行连接部分并使用处理程序对其进行更新。代码会是这样的:

在连接线程中通知 UI 活动...

mHandler.obtainMessage(Main_screen.MESSAGE_PGROGRESS_CHANGE_UPDATE, state, -1)
    .sendToTarget();

在 UI 活动中:

 private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (DEBUG)
        Log.i(this.getClass().getSimpleName(),
            "-> "
                + Thread.currentThread().getStackTrace()[2]
                    .getMethodName());
        switch (msg.what) {
        case MESSAGE_PGROGRESS_CHANGE_UPDATE:
        if (DEBUG)
            Log.i(this.getClass().getSimpleName(),
                "  MESSAGE_PGROGRESS_CHANGE_UPDATE: " + msg.arg1);

        // do your update of progressbar or whatever here
        break;
            case MESSAGE_PGROGRESS_CHANGE_SYNCHRINIZATION:
        if (DEBUG)
            Log.i(this.getClass().getSimpleName(),
                "  MESSAGE_PGROGRESS_CHANGE_SYNCHRINIZATION: " + msg.arg1);

        // do your update of progressbar or whatever here
        break;
于 2011-12-29T07:39:08.797 回答
0

HI 您可以使用 AsynTask 在后台进行通信并将结果显示到屏幕上。我希望这段代码可以帮助你。

public class PlasmaViewReDirectionTask extends
        AsyncTask<Void, String, String> {


    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        // showDialog("Fetching Video Url........");
        favDialog = new Dialog(PlasmaView.this,
                android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);

        favDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        favDialog.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        favDialog.setContentView(R.layout.busypopup);

        loadMessage = (TextView) favDialog
                .findViewById(R.id.loadingmessgetext);

        loadMessage.setText("Communicating with server........");

        favDialog.setCancelable(false);

        try {
            favDialog.show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.info("Dialog " + e.getMessage());
        }

    }

    @Override
    protected String doInBackground(Void... params) {

        String message = "";
        try {

            serverIpAddress = InetAddress.getByName("192.168.1.133");

            Log.d("TCP", "C: Connecting...");
            socketObject = new Socket(serverIpAddress, 8221);
            String str = "hi";
            try {
                Log.d("TCP", "C: Sending: '" + str + "'");
                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socketObject.getOutputStream())), true);
                out.println(str);

                inputStream = socketObject.getInputStream();

                inputDataStream = new DataInputStream(inputStream);

                message = inputDataStream.readUTF();
                Log.d("TCP", "C: Reply: '" + message + "'");

            } 
            catch(IOException e)
            {

                Log.e("TCP", "S: Error", e);
            }catch (Exception e) {

                Log.e("TCP", "S: Error", e);
            }

            finally {

                socketObject.close();
                Log.e("TCP", "S: Error");
            }

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            Log.e("TCP", "C: UnknownHostException", e);
            e.printStackTrace();
        } 
        catch(IOException e)
        {

            Log.e("TCP", "S: Error:", e);

         //Code to show Alert box with message "IOException"

        }
return message;
    }

    @Override
    protected void onPostExecute(String result) {

        try {
            if (favDialog.isShowing()) {
                favDialog.dismiss();
                favDialog = null;
            }
        } catch (Exception e1) {

        }
    Toast.makeText(YourScreen.this, result, Toast.LENGTH_LONG).show();


        super.onPostExecute(result);

    }

}
于 2013-06-10T12:01:15.127 回答