简体   繁体   中英

Java Android Loading spinner while connecting to a server

so I've made an app that connecting to a server in a certain port. while it tries to connect i want it to show a loading symbol. i tried this:

StartActivity.java:

package com.ed.istick;

public class StartActivity extends AppCompatActivity{
    private ProgressBar LS;
    private Button connectButt;
    private Button scanButt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);

    LS = (ProgressBar)findViewById(R.id.LodingSymbol);
    LS.setVisibility(View.GONE);

    final IntentIntegrator a = new IntentIntegrator(this); // `this` is the current Activity
    a.setCaptureActivity(CaptureActivityAnyOrientation.class);
    a.setOrientationLocked(false);
    connectButt = (Button) findViewById(R.id.ConnectButt);
    scanButt = (Button) findViewById(R.id.ScanButton);
    connectButt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //open the connect by Ip & pass screen
            final String IP = "10.0.0.2";
            final String pass = "hi";
            ClientLogic CL = null;
            try {
                if(createConnection(IP, pass)){
                    //connection created susecfully, open the template activity
                }
                else{
                    //ERROR
                    Globals g = Globals.getInstance();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

}


}

public boolean createConnection(final String IP, final String pass) throws IOException, InterruptedException {
    LS.setVisibility(View.VISIBLE);
    Globals g = Globals.getInstance();
    ClientLogic CL = new ClientLogic(IP, pass);
    Thread createClientLogic = new Thread(CL);
    createClientLogic.start();
    createClientLogic.join();

    LS.setVisibility(View.GONE);
    if(CL.getStatus()){
        g.setCL(CL);
        return true;
    }
    else{
        //connection didn't successful
        return false;
    }
}

ClientLogic.java:

public class ClientLogic implements Runnable{
    String IP;
    String pass;
    private Socket sock;
    private Queue<String> messagesToDiagnose;
    private Queue<String> messagesToSend;
    private DispatchMessage DM;
    private SendMessage SM;
    private boolean status;

public ClientLogic(String IP, String pass){
    messagesToDiagnose = new Queue<String>() {};
    messagesToSend = new Queue<String>() {};
    this.IP = IP;
    this.pass = pass;
    status = true;
}

public void addToDiagnose(String msg){
    this.messagesToDiagnose.add(msg);
}

public void addToSend(String msg){
    this.messagesToSend.add(msg);
}

public String getFirstDiagnose(){
    return this.messagesToDiagnose.remove();
}

public String getFirstSend(){
    return this.messagesToSend.remove();
}

public boolean processMassage(String msg){
    /*
    * TO DO: get the code from msg and do a switch case of what to do in a couple of situations
    * mostly when the server toss you out
     */
     int msgCode = Integer.parseInt(msg.substring(0, msg.indexOf('|')));
     switch(msgCode){
        case 100:
             //connection created susucfully
            break;

        case 102:
            //logout

        case 200:
            //connection error

        case 201:
            //iliagle Massage
     }
    return true;
}

public boolean getStatus(){
    return this.status;
}

public void setStatus(boolean status) {
    this.status = status;
}

@Override
public void run() {
    Globals g = Globals.getInstance();
    DataInputStream input = null;
    PrintStream output = null;
    try {
        this.sock = new Socket();
        this.sock.connect(new InetSocketAddress(IP, 6580), 10000);        
    } catch (IOException e) {
        status = false;
        g.setError(e.toString());
        g.setLoading(false);
        return;
    }
    try {
        input = new DataInputStream(sock.getInputStream());
        output = new PrintStream(sock.getOutputStream());

    }
    catch (IOException e) {
        System.out.println(e);
    }
    DM = new DispatchMessage(input, this);
    SM = new SendMessage(output, this);
    status = true;
    g.setLoading(false);
}
}

activity_start.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ed.istick.StartActivity">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="By Ip &amp; Pass"
    android:id="@+id/ConnectButt"
    android:textAllCaps="false"
    android:textColor="#FFFFFF"
    android:textSize="20sp"
    android:background="@drawable/barcode_button_shape"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Welcome To iStick"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:autoText="false" />

<ProgressBar
    android:id="@+id/LodingSymbol"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminate="true"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"/>

</RelativeLayout>

but it doesn't even show the logo. where did i got it wrong?

EDIT 1: I've changed the code a little bit and now it's show the logo and does all the view changes only after the connection thread is finished although the lines of code that does the view changes is before the thread run. (if the server is down what it does is basically is that the app will be freeze for 10 seconds then will show the logo). i want it to show the logo then try to connect

StartActivity.java (with the changes):

public class StartActivity extends AppCompatActivity{
    private ProgressBar LS;
    private Button connectButt;
    private Button scanButt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);

    LS = (ProgressBar)findViewById(R.id.LodingSymbol);
    LS.setVisibility(View.GONE);
    connectButt = (Button) findViewById(R.id.ConnectButt);
    scanButt = (Button) findViewById(R.id.ScanButton);

    final IntentIntegrator a = new IntentIntegrator(this); // `this` is the current Activity
    a.setCaptureActivity(CaptureActivityAnyOrientation.class);
    a.setOrientationLocked(false);

    connectButt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //open the connect by Ip & pass screen
            /*Intent loginScreen = new Intent(StartActivity.this, LoginActivity.class);
            startActivity(loginScreen);*/
            connectButt.setVisibility(View.INVISIBLE);
            scanButt.setVisibility(View.INVISIBLE);
            LS.setVisibility(View.VISIBLE);
            final String IP = "10.0.0.2";
            final String pass = "hi";
            ClientLogic CL = null;
            try {
                if(createConnection(IP, pass)){
                    //connection created susecfully, open the template activity
                    LS.setVisibility(View.GONE);
                }
                else{
                    //ERROR
                    Globals g = Globals.getInstance();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //connectButt.setVisibility(View.VISIBLE);
            //scanButt.setVisibility(View.VISIBLE);
        }
    });

    scanButt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            a.initiateScan();
        }
    });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    String contents = null;
    super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            contents = data.getStringExtra("SCAN_RESULT");
            String format = data.getStringExtra("SCAN_RESULT_FORMAT");
            // Handle successful scan
            final String IP = contents.substring(0, contents.indexOf('|'));
            final String pass = contents.substring(contents.indexOf('|') + 1, contents.length());
            try {
                if(createConnection(IP, pass)){
                    //connection created susecfully, open the template activity
                }
                else{
                    Globals g = Globals.getInstance();
                    Toast.makeText(this, "the scan didn't go as plan" + g.getError(), Toast.LENGTH_LONG).show();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        else if (resultCode == RESULT_CANCELED) {
            // Handle cancel
            Toast.makeText(this, "the scan didn't go as plan", Toast.LENGTH_LONG).show();
        }

}

public boolean createConnection(final String IP, final String pass) throws IOException, InterruptedException {
    Globals g = Globals.getInstance();
    g.setLoading(true);
    ClientLogic CL = new ClientLogic(IP, pass);
    Thread createClientLogic = new Thread(CL);
    createClientLogic.start();
    createClientLogic.join();
    if(CL.getStatus()){
        g.setCL(CL);
        return true;
    }
    else{
        //connection didn't sucssesfull
        return false;
    }
}

}

You do that :

LS.setVisibility(View.VISIBLE);
//some very fast operation
LS.setVisibility(View.GONE);

So it is normal that you don't even see it, you make it visible and directly gone.

You must call setVisibility(View.GONE) when your operation is finished. If your operation is very fast you won't even see it in any case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM