0

本来本来要在ActivityA中正常建立一个socket,准备发送数据,但是现在想在ActivityB中也能用同一个socket连接来传输数据。我在网上找了资料,好像可以用单例。我学了几天,还是不知道怎么下手,也找了一些练习的例子,但是还是不知道怎么用我原来的程序。

我想先在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);                        
    }   
}   

}

4

1 回答 1

1

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

即:在创建套接字连接的 MainActivity 中,
static YourSocketClass objSocket // which creates connection
并在另一个 Activity 中使用它,如下所示:MainActivity.objSocket.yourMethod(any_param)

通过声明静态你可以访问它。
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.

于 2015-03-14T06:24:07.793 回答