Android:How 使所有 activity 都可以使用套接字连接

Android:How to make all activity can use socket connections

我必须在 ActivityA 中正常建立套接字并准备发送数据, 不过现在想也可以用同一个socket连接来传输数据ActivityB.I 网上找了资料,好像可以用singleton.I 研究了几天,还是不知道怎么下手,找了一些练习题也不知道怎么用我原来的程序。

我想先在ActivityA和SERVER之间建立连接,并传一个值给SERVER,然后按下按钮切换到ActivityB,同时传值给SERVER

给点建议或者教学网站都可以,这样我才能继续研究下去,非常感谢

建立套接字方法:

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

}

您当然可以通过声明来使用它,

即:在创建套接字连接的 MainActivity 中,
<code>static YourSocketClass objSocket // which creates connection
并在另一个 Activity 中使用它,只需按如下方式调用它即:<code>MainActivity.objSocket.yourMethod(any_param) .

通过声明静态你可以访问它。
public static CommunicationClient objCommunicationClient; public boolean setConnection(final String ipAddress, final Context 上下文, 最终布尔值 isFromSearch) {</p> <pre><code> 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; }

} // 在我的另一个 Activity 中,我将其称为

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