简体   繁体   English

连接到服务器时的Java Android加载微调器

[英]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: 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: 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: 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. 编辑1:我稍稍更改了代码,现在它显示了徽标,并且仅在连接线程完成后所有视图才会更改,尽管执行视图更改的代码行在线程运行之前。 (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). (如果服务器停机,则基本上是将应用冻结10秒钟,然后显示徽标)。 i want it to show the logo then try to connect 我希望它显示徽标,然后尝试连接

StartActivity.java (with the changes): StartActivity.java(具有更改):

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. 操作完成后,必须调用setVisibility(View.GONE)。 If your operation is very fast you won't even see it in any case. 如果您的操作非常快,无论如何您都不会看到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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