0

通常、ActivityA でソケットを確立してデータを送信する準備ができていましたが、同じソケット接続を使用して ActivityB でデータを送信できるようにしたいと考えています。インターネットで情報を探したところ、使用できるようです。数日間勉強しましたが、まだ開始方法がわからず、演習の例もいくつか見つかりましたが、元のプログラムの使用方法はまだわかりません。

最初に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
それを別のアクティビティで使用するには、次のように呼び出しますMainActivity.objSocket.yourMethod(any_param)

static を宣言することでアクセスできます。
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 に答える