0

I had to establish a socket in ActivityA in normal and ready to send data, but now I want to also be able to use the same socket connection to transmit the data in ActivityB.I have looked for information on the Internet, it seems can use the singleton.I studied for a few days, I still don't know how to start, even find some examples of exercises too, but still do not know how to use my original program.

I want to first establish between ActivityA and SERVER connection, and to pass a value to the SERVER, then press the button to switch to ActivityB, and also transmit values to SERVER

Give me some advice or teaching sites can be, so that I can continue to study it, thank you very much

Establish socket methods:

public class MainActivity extends Activity {
Button Btn_Wifi,Btn_Power,Btn_Flame;
Boolean connected=false;    
Boolean powerstatus=false;  
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null ;
Socket socket = null;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainView();        
    setListensers();
    setButtonStatus();         
}   
private void mainView(){
    Btn_Wifi = (Button) findViewById(R.id.Btn_Wifi);
    Btn_Power = (Button) findViewById(R.id.Btn_Power);  
    Btn_Flame = (Button) findViewById(R.id.Btn_Flame);          
}
private void setListensers(){       
    Btn_Wifi.setOnClickListener(BtnWifiOnClickListener);
    Btn_Power.setOnClickListener(BtnPowerOnClickListener);  
    Btn_Flame.setOnClickListener(BtnFlameOnClickListener);      
}
private void setButtonStatus(){ 
    Btn_Power.setEnabled(false);    
    Btn_Flame.setEnabled(false);    
}   
Button.OnClickListener BtnWifiOnClickListener = new Button.OnClickListener(){
    @Override
    public void onClick(View view) {    
        if(!connected){ 
            try {
                socket = new Socket("IP", PORT);
                dataOutputStream = new DataOutputStream(socket.getOutputStream());//and stream
                changeConnectionStatus(true);//change the connection status                 
            }catch (UnknownHostException e) {
                changeConnectionStatus(false);
            }catch (IOException e) {
                changeConnectionStatus(false);
            }               
        }else{
            try {//try to close the socket            
                  socket.close();                                         
                  changeConnectionStatus(false);//change the connection status
             } catch (UnknownHostException e) {//catch and  
                 changeConnectionStatus(false);                   
             } catch (IOException e) {//catch and
                 changeConnectionStatus(false); 
             }
        }   
    }
};  
Button.OnClickListener BtnPowerOnClickListener = new Button.OnClickListener(){
    @Override
    public void onClick(View view) {            
        if(!powerstatus){
            try {
                byte[] pon ={(byte) 0x10,(byte) 0x10};
                dataOutputStream.write(pon); 
                dataOutputStream.flush();                                               
                PowerStatus(true);
            }catch(Exception obj){

                PowerStatus(false);
            }       
        }else{
            try {
                byte[] poff ={(byte) 0x11,(byte) 0x11};                                                         
                dataOutputStream.write(poff); //writeBytes(String str)  
                dataOutputStream.flush();  
                PowerStatus(false);
            }catch(Exception obj){
                PowerStatus(true);
            }           
            PowerStatus(false);
        }                       
    }
};  
Button.OnClickListener BtnFlameOnClickListener = new Button.OnClickListener(){
    @Override
    public void onClick(View view) {            
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, FlameActivity.class);
        startActivity(intent);
    }
};
public void changeConnectionStatus(Boolean isConnected) {
    connected=isConnected;//change variable 
    if(isConnected){//if connection established
        Btn_Wifi.setText("CONNECTED");
        Btn_Power.setEnabled(true);     

    }else{
        Btn_Wifi.setText("NOT WIFI");
        Btn_Power.setText("POWER OFF");
        Btn_Power.setEnabled(false);
        PowerStatus(false);

    }   
}
public void PowerStatus(Boolean isPowerOn) {
    powerstatus=isPowerOn;//change variable 
    if(isPowerOn){//if connection established
        Btn_Power.setText("POWER ON");          
        Btn_Flame.setText("SET FLAME");
        Btn_Flame.setEnabled(true);
    }else{
        Btn_Power.setText("POWER OFF");         
        Btn_Flame.setText("CANT SET FLAME");            
        Btn_Flame.setEnabled(false);                        
    }   
}   

}

Apar Amin
  • 653
  • 12
  • 22

1 Answers1

1

You can certainly use it by declaring,

i.e: in MainActivity which creates socket connection,
static YourSocketClass objSocket // which creates connection
and to use it in another Activity just called it as follow i.e:MainActivity.objSocket.yourMethod(any_param).

by declaring static you can access it.
public static CommunicationClient objCommunicationClient; public boolean setConnection(final String ipAddress, final Context context, final boolean isFromSearch) {

    class EstablishConnection extends AsyncTask<Void, Void, Boolean> {

        ProgressDialog objDialog;

        @Override
        protected void onPreExecute() {
            objDialog = new ProgressDialog(context);
            objDialog.setMessage(context.getResources().getString(
                    R.string.strConnecting));
            objDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            objDialog.show();
            objDialog.setCancelable(false);
            objDialog.setCanceledOnTouchOutside(false);
            super.onPreExecute();
        }

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

            boolean isConnected = false;
            boolean isValid = false;
            StrictMode.setThreadPolicy(policy);
            objCommunicationClient = new CommunicationClient(ipAddress);
            isSocketInitiated = objCommunicationClient.initSocket();
            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifiManager.getConnectionInfo();
            CommonUtils.SSID = info.getSSID();
            if (!isSocketInitiated) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(
                                getApplicationContext(),
                                getResources().getString(
                                        R.string.strCantConnect),
                                Toast.LENGTH_LONG).show();
                    }
                });

            } else {

                isConnected = true;
                if (!isFromSearch) {
                    CommonUtils.IP = ipAddress;
                    try {
                        objCommunicationClient.sendRequest(context,
                                "<APP_SPECIFIC>");

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    isValid = isFromSearch;
                }

                if (isValid) {
                    final Intent objIntentToGraph = new Intent(context,
                            GraphDataActivity.class);
                    objIntentToGraph
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            startActivity(objIntentToGraph);
                            overridePendingTransition(
                                    R.anim.slide_in_right,
                                    R.anim.slide_out_left);
                            finish();
                        }
                    });
                }
            }
            return isConnected;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            try {
                objDialog.cancel();
            } catch (Exception err) {
                err.printStackTrace();
            }
            super.onPostExecute(result);
        }

    }

    boolean status = false;
    try {
        status = new EstablishConnection().execute().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    return status;
}

} // and in my other Activity i called it as

            MainActivity_HomePage.objCommunicationClient.sendRequest(
                    context, CommonUtils.STOP_COMMAND); //send request is method which send message to server.

Apar Amin
  • 653
  • 12
  • 22
  • I do not understand, so, if I have several Activity for each Activity should call it? – Shane Jhan Mar 14 '15 at 07:37
  • @josh Jhan Yes you can easily access it even in your whole Application! – Apar Amin Mar 14 '15 at 09:44
  • Thank you for your answer,I am just a beginner, so Im not really familiar with the method you told me. I used to use `socket = new Socket("ipAddress", port); dataOutputStream = new DataOutputStream(socket.getOutputStream());` to establish connection, can I use the original code to adapt to your method? Or should I give up the original code? – Shane Jhan Mar 14 '15 at 15:50
  • dataOutputStream used to write something inshort to send message u can continue with your code, u just have to declare this in another class for convenience of sending and retrieving see my code above "CommunicationClient" serve exact same purpose which i am telling u and i am just instantiated in my MainActivity_HomePage with static so i can use it anywhere i want threw out application – Apar Amin Mar 15 '15 at 09:34
  • I maybe know how to do it ... but because I had way too simple, so be rewritten as you mentioned approach seems somewhat difficult! Im wondering if u can give me some advice about the method I wrote. – Shane Jhan Mar 15 '15 at 15:28
  • Down Voter care to share reason?? – Apar Amin Mar 24 '15 at 04:42
  • I do not know how to explain, but I will cancel the check is one of the reasons I did not solve my problem, so I'm afraid there may be other people who watch this will think that this question is to answer it, but maybe it is but I can not afford to get it done, – Shane Jhan Mar 24 '15 at 05:21
  • Another reason is that there are people I want to be able to continue to help me ... I avoid like the other articles of the questions people will say why I should be grateful he did not solve the problem, and then has been issued, but in fact I really did not solve my problem, if this idea is wrong then I am willing to cast a vote – Shane Jhan Mar 24 '15 at 05:24
  • @ShaneJhan no issue its your vote! you can do whatever you like, i just want to knew reason. although let me know if you really find other option apart from this let me be kind there is another way you can use singleton, from my person point of view i don't like to use it and it might add bit overhead so all my apps which is in market using this same concept and trust me we never face any issues, anyways best of luck. – Apar Amin Mar 24 '15 at 05:54
  • I really appreciate you ... I'm just a beginner, but I have my pressure .... I hope you do not cause trouble Thank you willing to give me so much advice, hoping that someone saw your answer to them is useful, I will continue working – Shane Jhan Mar 24 '15 at 12:03
  • if you have pressure than why you hurting other's reputations?? – Apar Amin Mar 24 '15 at 12:06
  • I didn't want to hurt anyone's reputation.I stress that I want to solve the problem, but I'm too weak, even though there are you so eager to answer, if such action is wrong and I am willing to sincerely apologize to vote cast back – Shane Jhan Mar 24 '15 at 12:17
  • Then buddy try to understand if you are weak and don't understand than why should you involved in down voting, you can down vote it, if it won't work but you can't down vote it due to lack of your understanding. – Apar Amin Mar 24 '15 at 12:22