PDA

View Full Version : بررسی اتصال از طریق سوکت و در background



mohammadr66
شنبه 15 خرداد 1395, 18:21 عصر
سلام به همه دوستان. من برنامه ای نوشتم تا اتصالی رو از طریق سوکت برقرار بکنه و اقدام به ارسال و دریافت داده از طریق سوکت بشه. مشکلی که دارم اینه که میخواهم وضعیت دائمی اتصال و برقراری صحیح اون در برنامه نشون داده بشه دقیقاً مثل اتصال به وای فای یا اینترنت و ... ولی نمیدونم چه طوری باید اینکارو انجام بدم. روشهایی در خصوص broadcastreceiver خوندم ولی نمیدونم دقیقاً باید چه روندی رو طی کنم. کد رو قرار میدم لطفاً دوستان راهنمایی کنید. وضعیت صحیح اتصال در texview2 نمایش داده میشه.



public class MainActivity extends Activity {
//TextView tv;
Button onoff;
static boolean connected = false;
MediaPlayer mp_on, mp_off;
AudioManager am;
//LinearLayout switch_container;
static ImageView lamp;
String Module_IP;


static final String NICKNAME = "MKN_CONNECTED";
//---socket---
InetAddress serverAddress;
Socket socket;


TextView textview1;
static TextView textview2;
Switch switch1;




//---thread for communicating on the socket---
CommsThread commsThread;


//---used for updating the UI on the main activity---
static Handler UIupdater = new Handler() {
@Override
public void handleMessage(Message msg) {
int numOfBytesReceived = msg.arg1;
byte[] buffer = (byte[]) msg.obj;


//---convert the entire byte array to string---
String strReceived = new String(buffer);


//---extract only the actual string received---
strReceived = strReceived.substring(
0, numOfBytesReceived);




if ( strReceived.contains("RELAY_ON") ){
lamp.setImageResource(R.drawable.l_on);
}


if ( strReceived.contains("RELAY_FF") ){
lamp.setImageResource(R.drawable.l_off);
}




//---display the text received on the TextView---
//txtMessagesReceived.setText(
// txtMessagesReceived.getText().toString() +
// strReceived);
}
};








private class CreateCommThreadTask extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
//---create a socket---
serverAddress =
InetAddress.getByName(Module_IP);
socket = new Socket(serverAddress, 8888);
commsThread = new CommsThread(socket);
commsThread.start();
//---sign in for the user; sends the nick name---
sendToServer(NICKNAME);
connected = true;


} catch (UnknownHostException e) {
Log.d("Sockets", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("Sockets", e.getLocalizedMessage());
}






return null;
}










}






private class WriteToServerTask extends AsyncTask
<byte[], Void, Void> {
protected Void doInBackground(byte[]...data) {
commsThread.write(data[0]);
return null;
}
}


private class CloseSocketTask extends AsyncTask
<Void, Void, Void> {
//@Override
protected Void doInBackground(Void... params) {
try {
//if(connected){
// socket.close();
// }


} catch (Exception e) {
//Log.d("Sockets", e.getLocalizedMessage());
Toast.makeText(getBaseContext(),"ErrInside",Toast.LENGTH_SHORT).show();
}
return null;
}
}






@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENT ATION_NOSENSOR);
setContentView(R.layout.activity_main);




textview1 = (TextView) findViewById(R.id.result_text);
textview1.setVisibility(View.INVISIBLE);




textview2 = (TextView) findViewById(R.id.textView_connected);
textview2.setVisibility(View.INVISIBLE);




switch1 = (Switch) findViewById(R.id.toggle_button_2);


switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {


if (isChecked) {


if (connected) {
sendToServer("MKN_ON");
textview1.setText("Send Ok");
textview1.setTextColor(Color.GREEN);
textview1.setVisibility(View.VISIBLE);
play_on();


} else {
Toast.makeText(MainActivity.this, "no conection", Toast.LENGTH_LONG).show();
}




} else {


if (connected) {
sendToServer("MKN_FF");
textview1.setText("OFF Sent Ok");
textview1.setTextColor(Color.RED);
textview1.setVisibility(View.VISIBLE);
play_off();


} else {
Toast.makeText(MainActivity.this, "no connection", Toast.LENGTH_SHORT).show();
}


}
}
});


if(connected) {
textview2.setText("Connection is true");
textview2.setTextColor(Color.GREEN);
textview2.setVisibility(View.VISIBLE);
} else{
textview2.setText("No connection");
textview2.setTextColor(Color.RED);
textview2.setVisibility(View.VISIBLE);


}






init();
main();
}








public void init(){
//tv = (TextView)findViewById(R.id.textView);
//onoff=(Button)findViewById(R.id.button2);




am = (AudioManager) getSystemService(AUDIO_SERVICE);
mp_on = MediaPlayer.create(this, R.raw.on);
mp_off = MediaPlayer.create(this, R.raw.off);


lamp = (ImageView) findViewById(R.id.imageView);


// switch_container =(LinearLayout) findViewById(R.id.key);
//---get the views---


}


public void main(){
//tv.setText(wifiIpAddress(this) );


final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
final String address = Formatter.formatIpAddress(dhcp.gateway);
//tv.setText(address + ":1394");
Module_IP = address;


try{
new CreateCommThreadTask().execute();


}catch(Exception e){
Log.d("Sockets","onResomeError");
}








}