2017-04-08 49 views
0

我正在創建一個android應用程序,我在一個活動中創建套接字連接,並使用共享首選項,並在另一個活動中獲取套接字變量做furthur作業,但它不工作,因爲我上午預計Socket連接thorugh共享首選項不工作

我的問題如何使用不同的actvities我exixting套接字連接找遍了它有像singltone類,Aysnc任務,一些術語,但我沒有得到它,如果singltone是在不同的活動中使用套接字連接的正確方法然後如何在下面的代碼中使用singlton類請su讓我改變...... !!!

否則是正確的方式我做共享PRef如下??也建議一些改變!

更新:對於建議

所以這裏標籤singlton是第一個活動

public class ipInfo extends AppCompatActivity { 
    EditText ipaddress;  
    String IPADD; 
    Integer PORT=null; 
    EditText portnum; 
    Button connect_btn; 
    StrictMode.ThreadPolicy policy; 
    Socket cs = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_ipinfo); 
    policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 
    ipaddress = (EditText)findViewById(R.id.editText); 
    portnum = (EditText)findViewById(R.id.editText2); 
    connect_btn =(Button)findViewById(R.id.button); 
    ip_check(); 
} 

public void ip_check(){ 
    connect_btn.setOnClickListener(
      new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        IPADD=ipaddress.getText().toString(); 
        PORT=Integer.parseInt(portnum.getText().toString()); 
        try { cs = new Socket(); 
          cs.connect(new InetSocketAddress(IPADD, PORT), 2000); 
          SharedPreferences sharedPreferences = getSharedPreferences("ipstore", Context.MODE_PRIVATE); 
          SharedPreferences.Editor editor = sharedPreferences.edit(); 
          editor.putString("ipadd",IPADD); 
          editor.putInt("port",PORT); 
          editor.commit(); 
          if(cs.isConnected()) { 
           Toast.makeText(ipInfo.this, "Connected", Toast.LENGTH_SHORT).show(); 
           Intent inst = new Intent(ipInfo.this,homeActivity.class); 
           startActivity(inst); 
           finish(); 
          } 
         }catch (IOException e) 
         {Toast.makeText(ipInfo.this,"Server is disconnected\n",Toast.LENGTH_SHORT).show(); 
         }catch (Exception e) 
         {Toast.makeText(ipInfo.this,e.getMessage(),Toast.LENGTH_SHORT).show();} 
       } 
      } 
    ); 
} 
} 

從這個活動我在下面活動

public class PowerActivity extends AppCompatActivity { 
    Button restart,shutdown,logof,sleep,abort; 
    StrictMode.ThreadPolicy policy; 
    Socket cs = null; 
    DataOutputStream out=null; 
    String SERVERIP; 
    int PORT; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_power); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    restart = (Button)findViewById(R.id.restart); 
    shutdown = (Button)findViewById(R.id.shutdown); 
    logof = (Button)findViewById(R.id.logof); 
    sleep = (Button)findViewById(R.id.sleep); 
    abort = (Button)findViewById(R.id.abort); 
    SharedPreferences sharedPreferences=getSharedPreferences("ipstore", Context.MODE_PRIVATE); 
    SERVERIP =sharedPreferences.getString("ipadd",""); 
    PORT=sharedPreferences.getInt("port", 8002); 
    Toast.makeText(this,"Working"+SERVERIP+"\n"+PORT,Toast.LENGTH_LONG).show();//this line working fine 
    policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 
    remotecmnd(); 
} 
public void remotecmnd(){ 
    restart.setOnClickListener(
      new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        //restart code 
         try{ 
          cs = new Socket(SERVERIP,PORT); 
          try{ 
           out = new DataOutputStream(cs.getOutputStream()); 
           out.writeUTF("restart"); 
           Toast.makeText(PowerActivity.this, "RESTART SUCCESS", Toast.LENGTH_LONG).show(); 
           } catch (Exception ea) { 
            Toast.makeText(PowerActivity.this, ea.getMessage(), Toast.LENGTH_LONG).show(); 
           } 
         }catch (IOException e) { 
          Toast.makeText(PowerActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); 
         } 
       } 
      } 
    ); 
} 
} 

這裏獲取值的服務器部分代碼

public class serverbackend extends Thread implements Runnable{ 
public static int SERVERPORT = 8002; 
public boolean running = false; 
public volatile boolean stop = false; 
public Socket client = null; 
ServerSocket sc = null; 
String value; 


public static void main(String[] args) { 
    mwcobj = new MainWindowController(); 
} 


@Override 
public void run() { 
    super.run(); 
    running = true; 
    try { 
     System.out.println("Server Has Started........ \nWaiting for client........"); 
     sc = new ServerSocket(SERVERPORT); 
     try { 
      while (!stop && running) { 
       client = sc.accept(); 
       System.out.println("Connection Accepted......"); 
       DataInputStream dis = new DataInputStream(client.getInputStream()); 
       value = dis.readUTF(); 

       switch (value) { 
       //Restart the system 
        case "restart": 
         System.out.println("Restarting"); 
         Runtime.getRuntime().exec("shutdown -r -t 10"); 
         break; 

       //some extra code 
        default: 
         break; 
       } 
      } 
     } catch (IOException e) { 
      System.out.println("Inner try catch "+e.getMessage()); 
     } 
    } catch (IOException e) { 
     System.out.println("Final try catch error "+e.getMessage()); 
    } 
} 


    public void requestStop(){ 
    try{ 
     stop = true; 
     sc.close(); 
     System.out.println("Server Has Stopped"); 
    }catch(IOException e){System.out.println("Server Stopped "+e.getMessage());} 


} 
    } 
+0

刪除所有StrictMode行代碼,並設法得到它在一個正常的方式運行在一個活動第一。你必須確實使用線程或AsyncTask。 – greenapps

回答

0

在我看來,我創建了一個藍牙通信的應用程序,在這裏我得到了同樣的問題,

答案的,這是使用getter和setter方法。這是很容易設置套接字和從其他Java類套接字,而不是發送活動,如果我遇到其他方法,我一定會告訴你的..

使用getter setter將爲你工作我beleive。

public class getset 
{ 


    static BluetoothSocket sock; 

    getset(BluetoothSocket sock) 
    { 
     this.sock=sock; 
    } 


    public static synchronized BluetoothSocket getSock() { 
     return sock; 
    } 

    public static synchronized void setSock(BluetoothSocket sock) { 
     getset.sock = sock; 
    } 
} 

在使用共享偏好的地方

setSock(socket); //socket is the Bluetoothsocket which you have to save 

Bluetoothsocket socket=getSock(); // to get value from the socket 

參考https://teamtreehouse.com/community/how-do-you-add-getters-and-setter-in-android-java

+0

但我不知道如何使用我的上述代碼部分! – Neel

+0

請參考上面的代碼,我添加了 –

+0

誠實地說我沒有得到它。你可以在我的代碼中使用你的代碼部分進行修改,因爲我不知道我應該在哪裏放置這個?我會感謝你的工作!謝謝 – Neel