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

时间:2011-12-29 07:34:48

标签: android progress-bar android-progressbar

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

 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"

            }
        }

那么在我从服务器获得回复之前应该如何让我的进度条可见。如果我得到答复,则应取消进度条。 任何人请帮助我...

3 个答案:

答案 0 :(得分: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});

答案 1 :(得分:0)

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

为避免您的主要用户活动被阻止,您需要在单独的线程中执行连接部分并使用Handler来更新它。代码就像:

在连接线程中通知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;

答案 2 :(得分:0)

<强> HI 您可以使用AsyncTask在后台进行服务器通信,并将结果显示在屏幕上。我希望这段代码可以帮助你。

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

    }

}