如何在连接服务器时显示进度条

发布于 2024-12-23 12:47:40 字数 2134 浏览 2 评论 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"

            }
        }

那么在我收到服务器回复之前应该做什么才能让我的进度条可见。如果我得到回复,进度条应该消失。 任何人请帮助我...

I want to show a progress bar in my activity which contains code to test server connection using socket. I want my progress bar to be visible only when sending data to server. As soon as i got reply from server, the progress should be dismissed and shows Alert box with message "Server busy". but in my screen the progress bar is visible after getting reply from server.Here is my code .

 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"

            }
        }

so what should be done to have my progress bar to be visible before i get reply from server. If i get reply, the progress bar should be dismissed.
Any one please help me...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

拥抱没勇气 2024-12-30 12:47:42

只需使用 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;

Just use mProgress.setVisibility(View.GONE) or mProgress.setVisibility(View.VISIBLE) to hide and show your widget.

To avoid that your main user activity gets blocked you need to do the connection part in a separate thread and use a Handler to update it. The code would be sth like:

In the connection thread to inform the UI activity...

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

In the UI activity:

 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;
一向肩并 2024-12-30 12:47:42


您可以使用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);

    }

}

HI
You can use AsynTask for doing severcommunication in background and display the result to screen. I hope this code helps you.

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);

    }

}
葬﹪忆之殇 2024-12-30 12:47:41

以下是我在使用 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});

Here is how I have implemented progressbar while authenticating a user using AsyncTask. See if this can help you

        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());
    }

}   

And called this from my LoginActivity as below

 new LoginTask(LoginActivity.this).execute(new String[]{userName, password});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文