How to make socket connection on Android - java

I'm trying to make a simple app that sends a message taken from an EditText,
using the Java Socket class. I'm trying with AsyncTask, but it works only once and I can't return the socket for reuse in another instance of the class.
Can you give me an example of a background service that opens a communication with a server and returns the Socket?
EDIT:
As required by nandsito; I intend to open a connection using a Button, so this button calls a beckground process that creates the connection with the server, finally returns the Socket. When I press another Button I want to start another task that reuses sockets, write data (for example Sring) receive a response from the server and updates the UI.

It looks simple but I think you have an interesting and challenging problem. If you want to keep the socket open after sending messages through it, you'll need to maintain one or more threads to use that socket because, you know, Android doesn't allow networking on main thread.
Multithread programming is seldom simple and often there is more than one way to do it. E.g. in Android you can use Handlers with Loopers from HandlerThreads, or the classic Java Thread. And also AsyncTask, but I think it doesn't fit this case.
How do you intend to manage the socket lifecycle (i.e. when is it opened or closed), and in which moments is data read/written from/into the socket? Please explain better the matter so I can suggest an implementation.
EDIT
Here's an example Activity with two buttons. One button runs an AsyncTask that creates a socket and its streams, and the other button runs another AsyncTask that writes data into the socket. It's an oversimplified solution, but it should work. Note that the code needs synchronization, for different threads access the socket.
public class MainActivity extends Activity {
private SocketContainer mSocketContainer;
private final Object mSocketContainerLock = new Object();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// onClick attribute of one button.
public void onClickPushMe(View view) {
String serverAddress;
int serverPort;
new CreateSocketAsyncTask(serverAddress, serverPort).execute();
}
// onClick attribute of other button.
public void onClickPushMeToo(View view) {
String text;
new WriteSocketAsyncTask(text).execute();
}
// Class that contains the socket and its streams,
// so they can be passed from one thread to another.
private class SocketContainer {
private Socket mSocket;
private InputStream mSocketInputStream;
private OutputStream mSocketOutputStream;
private SocketContainer(Socket socket, InputStream socketInputStream, OutputStream socketOutputStream) {
mSocket = socket;
mSocketInputStream = socketInputStream;
mSocketOutputStream = socketOutputStream;
}
private Socket getSocket() {
return mSocket;
}
private InputStream getSocketInputStream() {
return mSocketInputStream;
}
private OutputStream getSocketOutputStream() {
return mSocketOutputStream;
}
}
// AsyncTask that creates a SocketContainer and sets in into MainActivity.
private class CreateSocketAsyncTask extends AsyncTask<Void, Void, SocketContainer> {
private final String mServerAddress;
private final int mServerPort;
private CreateSocketAsyncTask(String serverAddress, int serverPort) {
mServerAddress = serverAddress;
mServerPort = serverPort;
}
protected SocketContainer doInBackground(Void... params) {
try {
Socket socket = new Socket(mServerAddress, mServerPort);
return new SocketContainer(socket, socket.getInputStream(), socket.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onPostExecute(SocketContainer socketContainer) {
super.onPostExecute(socketContainer);
synchronized (mSocketContainerLock) {
mSocketContainer = socketContainer;
}
}
}
private class WriteSocketAsyncTask extends AsyncTask<Void, Void, Void> {
private final String mText;
private WriteSocketAsyncTask(String text) {
mText = text;
}
#Override
protected Void doInBackground(Void... params) {
synchronized (mSocketContainerLock) {
try {
mSocketContainer.getSocketOutputStream().write(mText.getBytes(Charset.forName("UTF-8")));
mSocketContainer.getSocketOutputStream().flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return null;
}
}
}

With this code i connect to a chat, so you can use it similliary to connect with what you want
public class SocialConnectionManager extends AsyncTask<Void, Void, Void> {
public static final int SQL_STEP_LOGIN = 0;
public static final int SQL_STEP_LOGOUT = 1;
public static final int SQL_STEP_SEND = 2;
public static final int SQL_STEP_UPDATE = 3;
final int serverPort = 8080;
private String message, channel, userName, serverIp;
private int step;
private long uniqueId;
private Activity activity;
public SocialConnectionManager(String serverIp, long uniqueId, int step, String userName,
String channel, String message, Activity activity) {
this.message = message;
this.step = step;
this.uniqueId = uniqueId;
this.channel = channel;
this.userName = userName;
this.serverIp = serverIp;
this.activity = activity;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(serverIp, serverPort);
DataOutputStream dataOut = new DataOutputStream(socket.getOutputStream());
switch (step) {
case SQL_STEP_LOGIN:
dataOut.writeInt(step);
dataOut.writeLong(uniqueId);
dataOut.writeUTF(channel);
dataOut.writeUTF(userName);
break;
case SQL_STEP_LOGOUT:
dataOut.writeInt(step);
dataOut.writeLong(uniqueId);
dataOut.writeUTF(channel);
dataOut.writeUTF(userName);
break;
case SQL_STEP_SEND:
long messageId = createRandomId();
messageIds.add(messageId);
dataOut.writeInt(step);
dataOut.writeLong(uniqueId);
dataOut.writeUTF(channel);
dataOut.writeUTF(userName);
dataOut.writeUTF(message);
dataOut.writeLong(messageId);
break;
case SQL_STEP_UPDATE:
dataOut.writeInt(step);
dataOut.writeUTF(message);
break;
}
dataOut.flush();
} catch (UnknownHostException e) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
((MainActivity) activity).showNetworkAlertDialog(context.getString
(R.string.social_chat_connection_failed));
}
});
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
private class ReceiveTask extends AsyncTask {
final int clientPort = 5050;
#Override
protected Object doInBackground(Object[] params) {
try {
serverSocket = new ServerSocket(clientPort);
while (true) {
final Socket socket = serverSocket.accept();
DataInputStream dataIn = new DataInputStream(socket.getInputStream());
final int step = dataIn.readInt();
final int userCount = dataIn.readInt();
final String message = dataIn.readUTF();
final String userName = dataIn.readUTF();
switch (step) {
case SocialConnectionManager.SQL_STEP_LOGIN:
if (isLogging) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
showProgress(false);
}
});
isLogging = false;
isLoggedIn = true;
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
userCountView.setText(Integer.toString(userCount));
addMessage(message, userName, step);
}
});
break;
case SocialConnectionManager.SQL_STEP_LOGOUT:
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
addMessage(message, userName, step);
}
});
break;
case SocialConnectionManager.SQL_STEP_SEND:
messageId = dataIn.readLong();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
addMessage(message, userName, step);
}
});
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String ip = getIpAddress();
if (ip.equals("")) {
((MainActivity) activity).showNetworkAlertDialog(context.getString
(R.string.social_chat_connection_lost));
} else if (!deviceIp.equals(ip)) {
SocialConnectionManager socialConnectionManager =
new SocialConnectionManager(serverIp, 0,
SocialConnectionManager.SQL_STEP_UPDATE, null, null, deviceIp,
activity);
socialConnectionManager.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
};
}

Async task is not worthy for the real time chat.
Get into firebase to use the things easy.
This might help you-
https://www.firebase.com/docs/android/examples.html

Related

Why is my port source changing with every UDP message I send?

I'm tracking the UDP messages I'm sending from my android phone on Wireshark, but the source port number changes every time I send a message.
So I have two questions:
Is this bad if I want to receive messages back? Or would it be find, just each received message comes through a different port?
If the answer to 1) is yes it is bad, then what should I do to change that?
Here's my code:
edit: Full code
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int SERVERPORT = 1111;
public static final String SERVER_IP = "255.255.255.255";
private LinearLayout msgList;
private EditText edMessage;
private int clientTextColor;
private ClientThread clientThread;
private Thread thread;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgList = findViewById(R.id.msgList);
edMessage = findViewById(R.id.edMessage);
clientTextColor = ContextCompat.getColor(this, R.color.colorAccent);
handler = new Handler();
}
// Just for displaying messages on device
public TextView textView(String message, int color) {...}
public void showMessage(final String message, final int color) {
handler.post(new Runnable() {
#Override
public void run() {
msgList.addView(textView(message, color));
}
});
}
// Implementation
#Override
public void onClick(View view) {
if(view.getId() == R.id.clear) {
msgList.removeAllViews();
}
if (view.getId() == R.id.send_data) {
// Starting thread
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
String clientMessage = edMessage.getText().toString().trim(); // Client's Message
showMessage(clientMessage, Color.BLUE); // Just display
if (null != clientThread) {
clientThread.sendMessage(clientMessage + "\r\n");
}
}
}
class ClientThread implements Runnable {
byte[] buffer = new byte[1024];
#Override
public void run() {
try {
while (true) {
DatagramSocket ds = new DatagramSocket(SERVERPORT);
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String serverMsg = new String(dp.getData(), 0, dp.getLength());
showMessage("Server: " + serverMsg, clientTextColor);
ds.close();
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
}
void sendMessage(final String message) { // Called by "Send Data" button
new Thread(new Runnable() {
#Override
public void run() {
try {
byte[] msg = message.getBytes();
InetAddress ip = InetAddress.getByName(SERVER_IP);
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(msg, msg.length, ip, SERVERPORT);
socket.setBroadcast(true);
socket.send(packet);
} catch(Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
#Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}

Send a string through WiFi-Direct between two android devices

It is now over a month that I'm trying to send a string using WiFi-Direct between two android devices, but I'm still struggling hard to understand what I'm doing wrong.
I've looked around forums but they often don't give much detail on how to achieve what I want.
I also went through those two guides from the android developer's website:
Create P2P connections with Wi-Fi Direct
Wi-Fi Direct (peer-to-peer or P2P) overview
I'm using one activity - ActivityConnection - where I toggle the visibility of views depending on whether the user previously chose to send or to receive the string.
Immediatly, on the client side, discoverPeers() looks for any device with WiFi-Direct turned on and displays them on a ListView. Once the user chooses a device and presses the send button, the connection makes itself and the string is sent.
On the server side, the server is immediatly launched using my AsyncServerTask class. There, it waits for a client to connect and to retrieve its sent string.
My main problem is that, after choosing the device and tapping on the send button, the server side isn't receiving anything.
My second problem is that, sometimes, devices aren't being discovered and the listview stays empty.
Am I missing something? Or maybe doing something wrong?
Here's my current code.
I took the liberty to get rid of any line I thought to be out of context to make it easier to read.
ActivityConnection
public class ActivityConnection extends AppCompatActivity implements NewPeersListener {
public static final String CONNECTION_ACTOR = "actor";
public static final String SEND_INFO = "send";
public static final String RECEIVE_INFO = "receive";
ListView listViewDevices;
private IntentFilter intentFilter;
private WifiP2pManager manager;
private WifiP2pManager.Channel channel;
private WiFiDirectBroadcastReceiver receiver;
public List <WifiP2pDevice> listDevices;
private WifiP2pDevice selectedDevice;
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
connectToSelectedDevice();
}
});
Intent intent = this.getIntent();
String actor = intent.getStringExtra(CONNECTION_ACTOR);
this.intentFilter = new IntentFilter();
this.intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
this.intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
this.intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
this.intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
this.manager = (WifiP2pManager) this.getSystemService(Context.WIFI_P2P_SERVICE);
this.channel = this.manager.initialize(this, this.getMainLooper(), null);
this.receiver = new WiFiDirectBroadcastReceiver(this.manager, this.channel, this);
this.listDevices = new ArrayList <> ();
if (actor.equals(SEND_INFO)) {
DeviceAdapter adapter = new DeviceAdapter(ActivityConnection.this, R.layout.device_item, this.listDevices);
this.listViewDevices.setAdapter(adapter);
this.listViewDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedDevice = listDevices.get(position);
}
});
this.discoverPeers();
}
else if (actor.equals(RECEIVE_INFO)) {
new ServerAsyncTask(this).execute();
}
}
#Override
protected void onResume() {
super.onResume();
this.receiver = new WiFiDirectBroadcastReceiver(this.manager, this.channel, this);
this.registerReceiver(this.receiver, this.intentFilter);
}
#Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(this.receiver);
}
public void resultReceived (String result) {
Toast.makeText(ActivityConnection.this, "Received! :)", Toast.LENGTH_SHORT).show();
}
private void discoverPeers () {
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
// The discovery process succeeded
}
#Override
public void onFailure(int reason) {
// The discovery process DID NOT succeed
Toast.makeText(ActivityConnection.this, "Discovery process DID NOT succeed. Please verify that WiFi-Direct is active.", Toast.LENGTH_LONG).show();
}
});
}
private void connectToSelectedDevice () {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = this.selectedDevice.deviceAddress;
this.manager.connect(this.channel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
// Send string
Intent serviceIntent = new Intent(ActivityConnection.this, TransferService.class);
serviceIntent.setAction(TransferService.ACTION_SEND_STRING);
serviceIntent.putExtra(TransferService.EXTRAS_GROUP_OWNER_ADDRESS, getMacAddress());
serviceIntent.putExtra(TransferService.EXTRAS_GROUP_OWNER_PORT, 8090);
startService(serviceIntent);
onBackPressed();
}
#Override
public void onFailure(int reason) {
Toast.makeText(ActivityConnection.this, "Connection failed. Try again.", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
private String getMacAddress () {
try {
List <NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder result = new StringBuilder();
for (byte b : macBytes) {
result.append(String.format("%02X:",b));
}
if (result.length() > 0) {
result.deleteCharAt(result.length() - 1);
}
return result.toString();
}
} catch (Exception e) {
}
return "02:00:00:00:00:00";
}
#Override
public void newPeers (WifiP2pDeviceList wifiP2pDeviceList) {
this.listDevices = new ArrayList <> (wifiP2pDeviceList.getDeviceList());
DeviceAdapter adapter = new DeviceAdapter(ActivityConnection.this, R.layout.device_item, this.listDevices);
this.listViewDevices.setAdapter(adapter);
}
}
WiFiDirectBroadcastReceiver
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager manager;
private WifiP2pManager.Channel channel;
private ActivityConnection activity;
private List <NewPeersListener> listeners;
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel, ActivityConnection activity) {
super();
this.manager = manager;
this.channel = channel;
this.activity = activity;
this.listeners = new ArrayList <> ();
this.listeners.add(activity);
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wi-Fi P2P is enabled
} else {
// Wi-Fi P2P is not enabled
Toast.makeText(this.activity, "Please turn on WiFi-Direct (or WiFi-P2P).", Toast.LENGTH_SHORT).show();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// Request available peers from the wifi p2p manager.
if (this.manager != null) {
this.manager.requestPeers(this.channel, new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
for (NewPeersListener listener : listeners) {
listener.newPeers(peers);
}
}
});
}
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
}
}
}
ServerAsyncTask (server)
public class ServerAsyncTask extends AsyncTask<Void, Void, String> {
private ServerSocket serverSocket;
private Socket clientSocket;
private DataInputStream stream;
private WeakReference <Context> contextWeakReference;
ServerAsyncTask (Context context) {
this.contextWeakReference = new WeakReference <> (context);
}
#Override
protected String doInBackground (Void... params) {
try {
this.serverSocket = new ServerSocket(8090);
this.clientSocket = this.serverSocket.accept();
this.stream = new DataInputStream(this.clientSocket.getInputStream());
String received = this.stream.readUTF();
this.serverSocket.close();
return received;
} catch (IOException e) {
Log.e(TransferService.TAG, Objects.requireNonNull(e.getMessage()));
return null;
} finally {
if (this.stream != null) {
try {
this.stream.close();
} catch (IOException e) {
Log.e(TransferService.TAG, Objects.requireNonNull(e.getMessage()));
}
}
if (this.clientSocket != null) {
try {
this.clientSocket.close();
} catch (IOException e) {
Log.e(TransferService.TAG, Objects.requireNonNull(e.getMessage()));
}
}
if (this.serverSocket != null) {
try {
this.serverSocket.close();
} catch (IOException e) {
Log.e(TransferService.TAG, Objects.requireNonNull(e.getMessage()));
}
}
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute (String result) {
super.onPostExecute(result);
((ActivityConnection) this.contextWeakReference.get()).resultReceived(result);
}
}
TransferService (client)
public class TransferService extends IntentService {
public static final String TAG = "WIFI_DIRECT";
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_STRING = "sendString";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public TransferService (String name) {
super(name);
}
public TransferService () {
super("TransferService");
}
#Override
protected void onHandleIntent (Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_STRING)) {
String toSend = "string to send";
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
Socket socket = null;
DataOutputStream stream = null;
try {
// Create a client socket with the host, port, and timeout information.
socket = new Socket();
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(TAG, "Client connected socket - " + socket.isConnected());
// Send string
stream = new DataOutputStream(socket.getOutputStream());
stream.writeUTF(toSend);
stream.close();
Toast.makeText(context, "Sent! :)", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.e(TAG, Objects.requireNonNull(e.getMessage()));
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
In the ActivityConnetion class, I was giving a MAC address instead of an IP address. I don't know why I didn't see this, nor why I did it in the first place. So I looked around this forum and found out how to get the IP address of the WiFi-Direct's group owner: Wifi Direct Group Owner Address .
To get the code running, I went into the ActivityConnetion class, delete the getMacAddress() method and replaced this line:
serviceIntent.putExtra(TransferService.EXTRAS_GROUP_OWNER_ADDRESS, getMacAddress());
with this line:
serviceIntent.putExtra(TransferService.EXTRAS_GROUP_OWNER_ADDRESS, "192.168.49.1");
As the group owner's IP is always the same, one can write it down directly. As doing so can stop working if the IP changes, I would recommend looking for the group owner's IP instead. The link above show's how to do it.

Socket Connection thorugh Shared Preferences not working

I am creating an android application in which i am creating socket connection in one activity and using Shared Preferences and in another activity I am fetching the socket variables to do furthur jobs but its not working as i am expected
My question is how can i use my exixting socket connection in different actvities i have searched about it Got some terms like singltone class,Aysnc task, But i am not getting it,if singltone is proper way to use socket connetion in different activities then How can i use singlton class in following code please suggest me changes...!!!
Otherwise is it proper way am i doing Shared PRef as following??also suggest some changes!!!
UPDATE: Tagged singlton for suggestions
So here is First Activity
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();}
}
}
);
}
}
from this activity am fetching values in following activity
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();
}
}
}
);
}
}
here is server part code
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());}
}
}
In my opinion, I created a bluetooth communication app,where I get the same problem,
The answer for the this is to use getter and setter methods. It is very easy to set socket and get socket from other java class rather than sending across activities , If I came across other methods I will definitely will tell you on that..
Using getter setter will work for you I 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;
}
}
In the place of using shared preference
setSock(socket); //socket is the Bluetoothsocket which you have to save
Bluetoothsocket socket=getSock(); // to get value from the socket
refer https://teamtreehouse.com/community/how-do-you-add-getters-and-setter-in-android-java

How to access the activity object in Android

MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Client client = new Client();
try {
client.connect("192.168.1.10",5555);
} catch (IOException e) {
e.printStackTrace();
}
}
public void displayServerAnswer(String answer){
TextView textView = (TextView)findViewById(R.id.mainTextView);
textView.setText(answer);
}
...
Client.java
import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;
public class Client extends Observable implements Runnable {
private Socket socket;
private BufferedReader br;
private PrintWriter pw;
private boolean connected;
private int port=5555; //default port
private String hostName="localhost";//default host name
public Client() {
connected = false;
}
public void connect(String hostName, int port) throws IOException {
if(!connected)
{
this.hostName = hostName;
this.port = port;
socket = new Socket(hostName,port);
//get I/O from socket
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
connected = true;
//initiate reading from server...
Thread t = new Thread(this);
t.start(); //will call run method of this class
}
}
public void sendMessage(String msg) throws IOException
{
if(connected) {
pw.println(msg);
} else throw new IOException("Not connected to server");
}
public void run() {
String msg = ""; //holds the msg recieved from server
try {
while(connected && (msg = br.readLine())!= null)
{
//In Here I want to call MainActivity.displayServerAnswer()
//notify observers//
this.setChanged();
//notify+send out recieved msg to Observers
this.notifyObservers(msg);
}
}
catch(IOException ioe) { }
finally { connected = false; }
}
...
}
In the place I specified, I want to be able to display the server answer.
How can I get access to MainActivity instance that created client object, in order to call its method?
#hopia answer is pretty good. you also can implement the Listener Design pattern
public class Client extends Observable implements Runnable {
public interface ClientListener {
public void onAction();
}
private ClientListener mListener;
public Client(ClientListener listener) {
mListener = listener;
}
public class MainActivity extends ActionBarActivity implements ClientListener {
#Override
public void onAction(){
....do whatever you need
}
...
}
You can pass an acvtivity reference to your client in either a constructor or a set accessor method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Client client = new Client(this);
try {
client.connect("192.168.1.10",5555);
} catch (IOException e) {
e.printStackTrace();
}
}
And in your java object:
MainActivity activity;
public Client(MainActivity activity) {
connected = false;
this.activity = activity;
}
...
public void run() {
String msg = ""; //holds the msg recieved from server
try {
while(connected && (msg = br.readLine())!= null)
{
//In Here I want to call MainActivity.displayServerAnswer()
activity.displayServerAnswer();
//notify observers//
this.setChanged();
//notify+send out recieved msg to Observers
this.notifyObservers(msg);
}
}
catch(IOException ioe) { }
finally { connected = false; }
}
How about passing the activity instance as an argument to the Client's constructor?
// MainActivity
Client client = new Client(this);
// Client
public Client(Activity activity) {
this.activity = activity;
connected = false;
}

Custom Listener

I am working on a chat application. Currently i did like that when i open the ChatActvity, all sockets are registered and the chatting works... Now i want to change the coding structure.. I want to open the sockets in a class, not in Activity class and i need to add a listener to that class. How i implement this..?
private class Chatroom {
private static void initialise() {
// Initialising the sockets and registering listeners to each socket
}
}
I want to notify in my activity class when the socket listeners in the Chatroom class get called..
here is probably what you need :
public class RequestSender extends AsyncTask<String, Void, String> {
private final static String serverIP = "192.168.1.1";
private final static Integer serverPort = 1234;
private ServerResponseListener listener = null;
public void setServerResponseListener(ServerResponseListener listener){
this.listener=listener;
}
public interface ServerResponseListener {
public void onResponseReceive(String response);
}
#Override
protected String doInBackground(String... params) {
Socket socket = null;
try {
socket = new Socket(serverIP, serverPort);
} catch (IOException e) {
// return "server is unreachable" message or something
}
PrintWriter requestWriter = new PrintWriter(socket.getOutputStream());
BufferedReader resultReader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String request = params[0] //for example
requestWriter.println(request);
requestWriter.flush();
String result = null;
while ((result = resultReader.readLine()) != null) {}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
listener.onResponseReceive(result);
}
}
here is example how to execute AsynchTask from Activity :
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestSender requestSender = new RequestSender();
requestSender.setServerResponseListener(new RequestSender.ServerResponseListener(){
#override
public void onResponseReceive(String response){
//
}
});
requestSender.execute("message");
}
}
read this : http://developer.android.com/reference/android/os/AsyncTask.html

Categories