Search code examples
androidsocketsandroid-activitytcpsingleton-methods

Android:How to make all activity can use socket connections


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

}


Solution

  • 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.