connect via socket with a button - android

are days that I'm stuck with this problem. I created an application with the fragment and tabs, I have to insert a button that when clicked connects to a certain ip and to a certain port, I have no idea how to write and how to put it, they are only able to connect when it starts mainActivity, but I wish it were possible to control it by a button, can you help?

First, with last versions of Android framework all network operations can't be performed from the main thread (ie the thread that manage the UI). So, you need to use your own thread to make the connection.
An example:
package it.resis.solarapp.activities.fourcloud.application;
import it.resis.solarapp.R;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class CopyOfActivity4CloudConfiguration extends Activity {
private volatile Socket socket = null;
private boolean connectionOk = false;
private Button buttonDisconnect;
private Button buttonConnect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
buttonConnect = findViewById(R.id.buttonConnect);
buttonConnect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
InetSocketAddress addr = new InetSocketAddress("192.168.1.1", 80);
new ConnectToIpTask().execute(addr);
}
});
buttonDisconnect = findViewById(R.id.buttonDisconnect);
buttonConnect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
new CloseSocket().execute();
}
});
buttonDisconnect.setEnabled(false);
buttonConnect.setEnabled(true);
}
private class ConnectToIpTask extends AsyncTask<InetSocketAddress, Void, Boolean> {
#Override
protected Boolean doInBackground(InetSocketAddress... params) {
InetSocketAddress addr = params[0];
try {
socket = new Socket(addr.getAddress().toString(), addr.getPort());
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
connectionOk = result;
// update here the ui with result
if (result) {
buttonDisconnect.setEnabled(true);
buttonConnect.setEnabled(false);
}
}
}
private class CloseSocket extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
socket.close();
} catch (Exception ex) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
buttonDisconnect.setEnabled(false);
buttonConnect.setEnabled(true);
}
}
}

I could, I changed the line of code
from:
#Override
protected Boolean doInBackground(InetSocketAddress... params) {
InetSocketAddress addr = params[0];
try {
**socket = new Socket(addr.getAddress().toString(), addr.getPort());**
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
to
#Override
protected Boolean doInBackground(InetSocketAddress... params) {
InetSocketAddress addr = params[0];
try {
**socket = new Socket("192.168.1.1", 80);**
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
thanks to all

Related

EMDK Serial Communication Finds No Ports

I am trying to create an Android activity which sends data through the serial port as a product test. I have some code for doing so, which, so far, finds no serial ports on my device which definitely has a serial port. I intend to use this activity with a loopback connector on the serial port of the device to verify both the read and write functionalities. I have tried these two programs:
import android.app.Activity;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKManager.EMDKListener;
import com.symbol.emdk.EMDKManager.FEATURE_TYPE;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.serialcomm.SerialComm;
import com.symbol.emdk.serialcomm.SerialCommException;
import com.symbol.emdk.serialcomm.SerialCommManager;
import com.symbol.emdk.serialcomm.SerialCommResults;
import com.symbol.emdk.serialcomm.SerialPortInfo;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;
import java.util.List;
public class SerialTry3 extends Activity implements EMDKListener{
private String TAG = SerialTry3.class.getSimpleName();
private EMDKManager emdkManager = null;
private SerialComm serialCommPort = null;
private SerialCommManager serialCommManager = null;
private EditText txtDataToSend = null;
private TextView txtStatus = null;
private Button btnRead = null;
private Button btnWrite = null;
private Spinner spinnerPorts = null;
public HashMap<String, SerialPortInfo> supportedPorts = null;
#Override #SuppressWarnings("SetTextI18n")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.serial_try);
txtDataToSend = (EditText) findViewById(R.id.txtDataToSend);
txtDataToSend.setText("Serial Communication Write Data Testing.");
spinnerPorts = (Spinner)findViewById(R.id.spinnerPorts);
btnWrite = (Button) findViewById(R.id.btnWrite);
btnRead = (Button) findViewById(R.id.btnRead);
txtStatus = (TextView) findViewById(R.id.statusView);
txtStatus.setText("");
txtStatus.requestFocus();
EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
new AsyncStatusUpdate().execute("EMDKManager object request failed!");
}
new AsyncUiControlUpdate().execute(false);
}
#Override
public void onOpened(EMDKManager emdkManager) {
this.emdkManager = emdkManager;
Log.d(TAG, "EMDK opened");
try{
serialCommManager = (SerialCommManager) this.emdkManager.getInstance(FEATURE_TYPE.SERIALCOMM_EX);
if(serialCommManager != null) {
populatePorts();
}
else
{
new AsyncStatusUpdate().execute(FEATURE_TYPE.SERIALCOMM_EX.toString() + " Feature not supported.");
}
}
catch(Exception e)
{
Log.d(TAG, e.getMessage());
new AsyncStatusUpdate().execute(e.getMessage());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
deinitSerialComm();
if (emdkManager != null) {
emdkManager.release();
emdkManager = null;
}
}
#Override
protected void onPause()
{
super.onPause();
deinitSerialComm();
serialCommManager = null;
supportedPorts = null;
// Release the serialComm manager resources
if (emdkManager != null) {
emdkManager.release(FEATURE_TYPE.SERIALCOMM_EX);
}
}
#Override
protected void onResume()
{
super.onResume();
// Acquire the serialComm manager resources
if (emdkManager != null) {
serialCommManager = (SerialCommManager) emdkManager.getInstance(FEATURE_TYPE.SERIALCOMM_EX);
if (serialCommManager != null) {
populatePorts();
if (supportedPorts != null)
initSerialComm();
}
}
}
void populatePorts()
{
try {
if(serialCommManager != null) {
List<SerialPortInfo> serialPorts = serialCommManager.getSupportedPorts();
if(serialPorts.size()>0) {
supportedPorts = new HashMap<String, SerialPortInfo> ();
String[] ports = new String[serialPorts.size()];
int count = 0;
for (SerialPortInfo info : serialPorts) {
supportedPorts.put(info.getFriendlyName(), info);
ports[count] = info.getFriendlyName();
count++;
}
spinnerPorts.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, ports));
spinnerPorts.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//Disabling previous serial port before getting the new one
deinitSerialComm();
initSerialComm();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
else
{
new AsyncStatusUpdate().execute("Failed to get available ports");
Toast.makeText(this, "Failed to get available ports, serial communication may not be supported.", Toast.LENGTH_LONG).show();
finish();
}
}
else
{
new AsyncStatusUpdate().execute("SerialCommManager is null");
}
}
catch (Exception ex)
{
Log.d(TAG, ex.getMessage());
new AsyncStatusUpdate().execute(ex.getMessage());
}
}
void initSerialComm() {
new AsyncEnableSerialComm().execute(supportedPorts.get(spinnerPorts.getSelectedItem()));
}
#Override
public void onClosed() {
if(emdkManager != null) {
emdkManager.release();
}
new AsyncStatusUpdate().execute("EMDK closed unexpectedly! Please close and restart the application.");
}
public void btnReadOnClick(View arg)
{
new AsyncReadData().execute();
}
public void btnWriteOnClick(View arg)
{
new AsyncUiControlUpdate().execute(false);
try {
String writeData = txtDataToSend.getText().toString();
int bytesWritten = serialCommPort.write(writeData.getBytes(), writeData.getBytes().length);
new AsyncStatusUpdate().execute("Bytes written: "+ bytesWritten);
} catch (SerialCommException e) {
new AsyncStatusUpdate().execute("write: "+ e.getResult().getDescription());
}
catch (Exception e) {
new AsyncStatusUpdate().execute("write: "+ e.getMessage() + "\n");
}
new AsyncUiControlUpdate().execute(true);
}
void deinitSerialComm() {
if (serialCommPort != null) {
try {
serialCommPort.disable();
serialCommPort = null;
} catch (Exception ex) {
Log.d(TAG, "deinitSerialComm disable Exception: " + ex.getMessage());
}
}
}
#SuppressWarnings("StaticFieldLeak")
private class AsyncStatusUpdate extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return params[0];
}
#Override
protected void onPostExecute(String result) {
txtStatus.setText(result);
}
}
#SuppressWarnings("StaticFieldLeak")
private class AsyncUiControlUpdate extends AsyncTask<Boolean, Void, Boolean> {
#Override
protected Boolean doInBackground(Boolean... arg0) {
return arg0[0];
}
#Override
protected void onPostExecute(Boolean bEnable) {
btnRead.setEnabled(bEnable);
btnWrite.setEnabled(bEnable);
txtDataToSend.setEnabled(bEnable);
spinnerPorts.setEnabled(bEnable);
}
}
#SuppressWarnings("StaticFieldLeak")
private class AsyncEnableSerialComm extends AsyncTask<SerialPortInfo, Void, SerialCommResults>
{
#Override
protected SerialCommResults doInBackground(SerialPortInfo... params) {
SerialCommResults returnvar = SerialCommResults.FAILURE;
try {
serialCommPort = serialCommManager.getPort(params[0]);
} catch (Exception ex) {
ex.printStackTrace();
}
if (serialCommPort != null) {
try {
serialCommPort.enable();
returnvar = SerialCommResults.SUCCESS;
} catch (SerialCommException e) {
Log.d(TAG, e.getMessage());
e.printStackTrace();
returnvar = e.getResult();
}
}
return returnvar;
}
#Override #SuppressWarnings("SetTextI18n")
protected void onPostExecute(SerialCommResults result) {
super.onPostExecute(result);
if (result == SerialCommResults.SUCCESS) {
new AsyncStatusUpdate().execute("Serial comm channel enabled: (" + spinnerPorts.getSelectedItem().toString() + ")");
txtDataToSend.setText("Serial Communication Write Data Testing " + spinnerPorts.getSelectedItem().toString() + ".");
new AsyncUiControlUpdate().execute(true);
} else {
new AsyncStatusUpdate().execute(result.getDescription());
new AsyncUiControlUpdate().execute(false);
}
}
}
#SuppressWarnings("StaticFieldLeak")
private class AsyncReadData extends AsyncTask<Void, Void, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
new AsyncUiControlUpdate().execute(false);
new AsyncStatusUpdate().execute("Reading..");
}
#Override
protected String doInBackground(Void... params) {
String statusText = "";
try {
byte[] readBuffer = serialCommPort.read(10000); //Timeout after 10 seconds
if (readBuffer != null) {
String tempString = new String(readBuffer);
statusText = "Data Read:\n" + tempString;
} else {
statusText = "No Data Available";
}
} catch (SerialCommException e) {
statusText = "read:" + e.getResult().getDescription();
} catch (Exception e) {
statusText = "read:" + e.getMessage();
}
return statusText;
}
#Override
protected void onPostExecute(String statusText) {
super.onPostExecute(statusText);
new AsyncUiControlUpdate().execute(true);
new AsyncStatusUpdate().execute(statusText);
}
}
}
and
import android.app.Activity;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKManager.FEATURE_TYPE;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.serialcomm.SerialComm;
import com.symbol.emdk.serialcomm.SerialCommException;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.symbol.emdk.serialcomm.SerialCommManager;
import com.symbol.emdk.serialcomm.SerialPortInfo;
import java.util.List;
public class SerialTry extends Activity implements EMDKManager.EMDKListener {
private String TAG = SerialTry.class.getSimpleName();
private EMDKManager emdkManager = null;
private SerialComm serialComm = null;
private SerialCommManager serialCommMan = null;
private EditText editText = null;
private TextView statusView = null;
private Button readButton = null;
private Button writeButton = null;
#Override #SuppressWarnings("SetTextI18n")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.serial_try);
editText = (EditText) findViewById(R.id.editText1);
editText.setText("Serial Communication Write Data Testing.");
statusView = (TextView) findViewById(R.id.statusView);
statusView.setText("");
statusView.requestFocus();
EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
statusView.setText("Failed to open EMDK");
} else {
statusView.setText("Opening EMDK...");
}
//
// Get the serialComm/port object by passing a SerialPortInfo object:
addReadButtonEvents();
writeButtonEvents();
setEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (emdkManager != null) {
emdkManager.release();
emdkManager = null;
}
}
#Override
public void onOpened(EMDKManager emdkManager) {
this.emdkManager = emdkManager;
Log.d(TAG, "EMDK opened");
try{
serialCommMan = (SerialCommManager) this.emdkManager.getInstance(EMDKManager.FEATURE_TYPE.SERIALCOMM_EX);
List<SerialPortInfo> serialPorts = serialCommMan.getSupportedPorts();
serialComm = serialCommMan.getPort(serialPorts.get(0));
System.out.println("Supported Ports::::::" + serialPorts);
Thread readThread = new Thread(new Runnable() {
#Override
public void run() {
String statusText;
if (serialComm != null) {
try{
serialComm.enable();
statusText = "Serial comm channel enabled";
setEnabled(true);
} catch(SerialCommException e){
Log.d(TAG, e.getMessage());
e.printStackTrace();
statusText = e.getMessage();
setEnabled(false);
}
} else {
statusText = FEATURE_TYPE.SERIALCOMM_EX.toString() + " Feature not supported or initilization error.";
setEnabled(false);
}
displayMessage(statusText);
}
});
readThread.start();
}
catch(Exception e)
{
Log.d(TAG, e.getMessage());
e.printStackTrace();
displayMessage(e.getMessage());
}
}
#Override
public void onClosed() {
if(emdkManager != null) {
emdkManager.release();
}
displayMessage("EMDK closed abruptly.");
}
private void addReadButtonEvents() {
readButton = (Button) findViewById(R.id.btnRead);
readButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread readThread = new Thread(new Runnable() {
#Override
public void run() {
setEnabled(false);
String statusText;
try {
byte[] readBuffer = serialComm.read(10000); //Timeout after 10 seconds
if(readBuffer != null) {
String tempString = new String(readBuffer);
statusText = "Data Read:\n" + tempString;
} else {
statusText = "No Data Available";
}
}catch (SerialCommException e) {
statusText ="read:"+ e.getResult().getDescription();
e.printStackTrace();
}
catch (Exception e) {
statusText = "read:"+ e.getMessage();
e.printStackTrace();
}
setEnabled(true);
displayMessage(statusText);
}
});
readThread.start();
}
});
}
#SuppressWarnings("SetTextI18n")
private void writeButtonEvents() {
writeButton = (Button) findViewById(R.id.btnWrite);
writeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setEnabled(false);
try {
String writeData = editText.getText().toString();
int bytesWritten = serialComm.write(writeData.getBytes(), writeData.getBytes().length);
statusView.setText("Bytes written: "+ bytesWritten);
} catch (SerialCommException e) {
statusView.setText("write: "+ e.getResult().getDescription());
}
catch (Exception e) {
statusView.setText("write: "+ e.getMessage() + "\n");
}
setEnabled(true);
}
});
}
#SuppressWarnings("SetTextI18n")
void displayMessage(String message) {
final String tempMessage = message;
runOnUiThread(new Runnable() {
public void run() {
statusView.setText(tempMessage + "\n");
}
});
}
void setEnabled(boolean enableState) {
final boolean tempState = enableState;
runOnUiThread(new Runnable() {
public void run() {
readButton.setEnabled(tempState);
writeButton.setEnabled(tempState);
editText.setEnabled(tempState);
}
});
}
}
Does the problem seem to be with my code or is there something I am not understanding about the device itself? Any help would be appreciated. Thank you for your time.

Zebra RFD2000 TC20 RFID SDK

I am using the quick start example supplied in the Android developer guide (rfid-sdk-for-android-dg-en.pdf) and although it does work and scans RFID TAGS there seems to be a problem with the reliability of the scanning. I have tracked the problem down to the EventHandler Class, that the reader.Actions.getReadTags method sometimes returns null this is even if the RFID tags are next to the scanner.
Any help would be much appreciated
I have included the code that I am using:
package uk.co.assettrac.rfd2000_tc20_example;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.zebra.rfid.api3.*;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static Readers readers;
private static ArrayList<ReaderDevice> availableRFIDReaderList;
private static ReaderDevice readerDevice;
private static RFIDReader reader;
private static String TAG = "DEMO";
TextView textView;
private EventHandler eventHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// UI
textView = (TextView) findViewById(R.id.TagText);
// SDK
if (readers == null) {
readers = new Readers(this, ENUM_TRANSPORT.SERVICE_SERIAL);
}
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
try {
if (readers != null) {
if (readers.GetAvailableRFIDReaderList() != null) {
availableRFIDReaderList =
readers.GetAvailableRFIDReaderList();
if (availableRFIDReaderList.size() != 0) {
// get first reader from list
readerDevice = availableRFIDReaderList.get(0);
reader = readerDevice.getRFIDReader();
if (!reader.isConnected()) {
// Establish connection to the RFID Reader
reader.connect();
ConfigureReader();
return true;
}
}
}
}
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
Log.d(TAG, "OperationFailureException " + e.getVendorMessage());
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean) {
Toast.makeText(getApplicationContext(), "Reader Connected",
Toast.LENGTH_LONG).show();
//textView.setText("Reader connected");
}
}
}.execute();
}
private void ConfigureReader() {
if (reader.isConnected()) {
TriggerInfo triggerInfo = new TriggerInfo();
triggerInfo.StartTrigger.setTriggerType(START_TRIGGER_TYPE.START_TRIGGER_TYPE_IMMEDIATE);
triggerInfo.StopTrigger.setTriggerType(STOP_TRIGGER_TYPE.STOP_TRIGGER_TYPE_IMMEDIATE);
try {
// receive events from reader
if (eventHandler == null)
eventHandler = new EventHandler();
reader.Events.addEventsListener(eventHandler);
// HH event
reader.Events.setHandheldEvent(true);
// tag event with tag data
reader.Events.setTagReadEvent(true);
reader.Events.setAttachTagDataWithReadEvent(true);
// set trigger mode as rfid so scanner beam will not come
reader.Config.setTriggerMode(ENUM_TRIGGER_MODE.RFID_MODE, true);
// set start and stop triggers
reader.Config.setStartTrigger(triggerInfo.StartTrigger);
reader.Config.setStopTrigger(triggerInfo.StopTrigger);
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (reader != null) {
reader.Events.removeEventsListener(eventHandler);
reader.disconnect();
Toast.makeText(getApplicationContext(), "Disconnecting reader",
Toast.LENGTH_LONG).show();
reader = null;
readers.Dispose();
readers = null;
}
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read/Status Notify handler
// Implement the RfidEventsLister class to receive event notifications
public class EventHandler implements RfidEventsListener {
// Read Event Notification
public void eventReadNotify(RfidReadEvents e) {
// Recommended to use new method getReadTagsEx for better performance in case of large tag population
TagData[] myTags = reader.Actions.getReadTags(100);
if (myTags != null) {
for (int index = 0; index < myTags.length; index++) {
Log.d(TAG, "Tag ID " + myTags[index].getTagID());
if (myTags[index].getOpCode() ==
ACCESS_OPERATION_CODE.ACCESS_OPERATION_READ &&
myTags[index].getOpStatus() ==
ACCESS_OPERATION_STATUS.ACCESS_SUCCESS) {
if (myTags[index].getMemoryBankData().length() > 0) {
Log.d(TAG, " Mem Bank Data " + myTags[index].getMemoryBankData());
}
}
}
} else {
Log.d(TAG, "TagData Array Null");
}
}
// Status Event Notification
public void eventStatusNotify(RfidStatusEvents rfidStatusEvents) {
Log.d(TAG, "Status Notification: " +
rfidStatusEvents.StatusEventData.getStatusEventType());
if (rfidStatusEvents.StatusEventData.getStatusEventType() ==
STATUS_EVENT_TYPE.HANDHELD_TRIGGER_EVENT) {
if
(rfidStatusEvents.StatusEventData.HandheldTriggerEventData.getHandheldEvent() ==
HANDHELD_TRIGGER_EVENT_TYPE.HANDHELD_TRIGGER_PRESSED) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
try {
reader.Actions.Inventory.perform();
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
if (rfidStatusEvents.StatusEventData.HandheldTriggerEventData.getHandheldEvent() ==
HANDHELD_TRIGGER_EVENT_TYPE.HANDHELD_TRIGGER_RELEASED) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
try {
reader.Actions.Inventory.stop();
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
}
}
}
}
After reading the docs for a long time I found that the line
reader.Events.setAttachTagDataWithReadEvent(true);
was causing the problem.

Sending data from Arduino to Android

I have been trying to send data from arduino to an Android application via Bluetooth Module HC-05 and i couldn't get any readings from the arduino to be displayed in the application
The arduino code is :
void setup() {
Serial.begin(9600);
}
void loop()
{
char c;
if(Serial.available())
{
c = Serial.read();
Serial.print(c);
}
}
The Android code is:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
// private final String DEVICE_NAME="MyBTBee";
private final String DEVICE_ADDRESS="30:14:12:18:01:38";
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//Serial Port Service ID
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Button startButton, sendButton,clearButton,stopButton;
TextView textView;
EditText editText;
boolean deviceConnected=false;
Thread thread;
byte buffer[];
int bufferPosition;
boolean stopThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button) findViewById(R.id.buttonStart);
sendButton = (Button) findViewById(R.id.buttonSend);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
setUiEnabled(false);
}
public void setUiEnabled(boolean bool)
{
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public boolean BTinit()
{
boolean found=false;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if(bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
}
else
{
for (BluetoothDevice iterator : bondedDevices)
{
if(iterator.getAddress().equals(DEVICE_ADDRESS))
{
device=iterator;
found=true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
boolean connected=true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
connected=false;
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
return connected;
}
public void onClickStart(View view) {
if(BTinit())
{
if(BTconnect())
{
setUiEnabled(true);
deviceConnected=true;
beginListenForData();
textView.append("\nConnection Opened!\n");
}
}
}
void beginListenForData()
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopThread)
{
try
{
int byteCount = inputStream.available();
if(byteCount > 0)
{
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String string=new String(rawBytes,"UTF-8");
handler.post(new Runnable() {
public void run()
{
textView.append(string);
}
});
}
}
catch (IOException ex)
{
stopThread = true;
}
}
}
});
thread.start();
}
public void onClickSend(View view) {
String string = editText.getText().toString();
string.concat("\n");
try {
outputStream.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append("\nSent Data:"+string+"\n");
}
public void onClickStop(View view) throws IOException {
stopThread = true;
outputStream.close();
inputStream.close();
socket.close();
setUiEnabled(false);
deviceConnected=false;
textView.append("\nConnection Closed!\n");
}
public void onClickClear(View view) {
textView.setText("");
}
}
The first issue I see right now is in your Arduino code:
You're never sending the message over Bluetooth as you're using the same Serial for input and output. If you're using an Arduino Mega using Serial1 would fixe this (Using TX1 and RX1). If you're not using a Mega you should consider to use the SerialSoftware library which allows you to create a new custom Serial.
It would be nice to see your Arduino setup to see how you wired it up.
Hope that helps you, feel free to ask any question.

Unable to connect to the bluetooth Module

This weekend, I decided to work with arduino. Currently I am facing a difficulty in connecting my phone to Arduino. I have successfully passed the address of the module to ledControl.java. I am using AsyncTask to carry out the operation for connecting to arduino. Can anyone pls guide me.
NOTE: m unable to connect with any of the devices having bluetooth.
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
/**
* Created by milind on 09/01/16.
*/
public class ledControl extends Activity {
Button btnOn, btnOff, btnDis;
SeekBar brightness;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.led_control);
//receive the address of the bluetooth device
Intent newint = getIntent();
address = newint.getStringExtra("address");
Log.wtf("ledControl Address:", address); // Log value received.
//view of the ledControl layout
//call the widgtes
btnOn = (Button) findViewById(R.id.on);
btnOff = (Button) findViewById(R.id.off);
//btnDis = (Button)findViewById(R.id.button4);
//brightness = (SeekBar)findViewById(R.id.seekBar);
new ConnectBT().execute(address);
btnOn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
btnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("1".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("2".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private class ConnectBT extends AsyncTask<String, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
Log.i("ledControl","Device Connecting");
//progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(String... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
Log.wtf("ledControl","AsyncTask Called");
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
Log.wtf("AsyncTask:",address);
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(devices[0]);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
Log.i("ledControl:","Connected to Device.");
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again."); // This toast is produced everytime.
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
//progress.dismiss();
}
}
private void msg(final String s)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
});
}
}
In the end, I get this Toast message. "Connection Failed. Is it a SPP Bluetooth? Try again."

Android connection refuses sometimes (Not all times)

I wrote a WiFi-Direct Code connection and created a connection between them, then I created a ServerSocket on the first side and a Socket on the client side and started sending data between them, the first time I start the application it works Successfully, but when I close the Application and start it again it gives me an exception that says "Connection Refused ECONNREFUSED"
here is my code in the Server side:
package com.example.serverwifidirect;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class BroadcastServer extends BroadcastReceiver
{
#SuppressLint("NewApi")
private WifiP2pManager mManager;
private Channel mChannel;
private Server mActivity;
static boolean temp=false;
Socket client=null;
static boolean isRunning = false;
ServerSocket serverSocket = null;
InetSocketAddress inet;
private void closeConnections()
{
try
{
if(client!=null || serverSocket!=null)
{
if(client!=null)
{
if(client.isInputShutdown()|| client.isOutputShutdown())
{
log("x1");
client.close();
}
if(client.isConnected())
{
log("x2");
client.close();
log("x2.1");
//client.bind(null);
log("x2.2");
}
if(client.isBound())
{
log("x3");
client.close();
}
client=null;
}
}
}
catch(Exception e)
{
log("Error :'(");
e.printStackTrace();
}
}
#SuppressLint("NewApi")
public BroadcastServer(WifiP2pManager manager, Channel channel, Server activity)
{
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
try
{
serverSocket = new ServerSocket(8870);
serverSocket.setReuseAddress(true);
}
catch(Exception e)
{
}
}
#SuppressLint("NewApi")
#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)
{}
else
{}
}
else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
mManager.requestPeers(mChannel, new PeerListListener()
{
#Override
public void onPeersAvailable(WifiP2pDeviceList list)
{
}
});
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action))
{
Bundle b = intent.getExtras();
NetworkInfo info = (NetworkInfo)b.get(WifiP2pManager.EXTRA_NETWORK_INFO);
if(info.isFailover())
{
temp=false;
}
else if(info.isConnected())
{
temp=true;
log("c1");
new Thread(new Runnable(){
public void run()
{
try
{
client =serverSocket.accept();
InputStream input=null;
input = client.getInputStream();
log("q3");
while(BroadcastServer.temp)
{
final int n = input.read();
if(n==100)
{
closeConnections();
mManager.cancelConnect(mChannel, new ActionListener() {
#Override
public void onSuccess()
{
log("done");
mManager.removeGroup(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("group removed");
}
#Override
public void onFailure(int reason)
{
log("fail!!!!!");
}
});
}
#Override
public void onFailure(int reason) {
log("fail");
mManager.removeGroup(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("group removed");
}
#Override
public void onFailure(int reason)
{
log("fail!!!!!");
}
});
}
});
}
log("q4");
if(n==-1)
{
log("n = -1");
break;
}
log("n= "+n);
mActivity.runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(mActivity.getBaseContext(), "--"+n, Toast.LENGTH_SHORT).show();
}
});
}
log("After loop");
}
catch(Exception e)
{
}
}
});
mActivity.runOnUiThread(new Runnable(){
public void run()
{
//Toast.makeText(mActivity, "Connected to WiFi-Direct!", Toast.LENGTH_SHORT).show();
}
});
log("c2");
}
else if(info.isConnectedOrConnecting())
{
temp=false;
}
else if(!info.isConnected())
{
temp=false;
try
{
if(client!=null || serverSocket!=null)
{
if(client!=null)
{
if(client.isInputShutdown()|| client.isOutputShutdown())
{
log("x1");
client.close();
}
if(client.isConnected())
{
log("x2");
client.close();
log("x2.1");
//client.bind(null);
log("x2.2");
}
if(client.isBound())
{
log("x3");
client.close();
}
client=null;
}
}
}
catch(Exception e)
{
log("Error :'(");
e.printStackTrace();
}
mManager.clearLocalServices(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("success");
}
#Override
public void onFailure(int reason)
{
}
});
}
}
else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action))
{
log("Device change Action!");
}
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
this code is in the Server side, and the following code is in the Client side:
package com.example.wifidirect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
#SuppressLint("NewApi")
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver
{
static WifiP2pDevice connectedDevice = null;
boolean found=false;
boolean connected = false;
private WifiP2pManager mManager;
private Channel mChannel;
Button find = null;
Activity mActivity = null;
#SuppressLint("NewApi")
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel, WifiDirect activity)
{
super();
this.mManager = manager;
this.mChannel = channel;
mActivity = activity;
find = (Button)mActivity.findViewById(R.id.discover);
}
#SuppressLint("NewApi")
#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)
{
// Wifi Direct is enabled
} else
{
// Wi-Fi Direct is not enabled
}
}
else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
mManager.requestPeers(mChannel, new PeerListListener()
{
#Override
public void onPeersAvailable(WifiP2pDeviceList list)
{
WifiP2pDevice d = null;
if(!found)
{
Log.d("status", "2");
Collection<WifiP2pDevice>li = list.getDeviceList();
ArrayList<WifiP2pDevice> arrayList = new ArrayList<WifiP2pDevice>();
Iterator<WifiP2pDevice>peers = li.iterator();
while(peers.hasNext())
{
WifiP2pDevice device = peers.next();
arrayList.add(device);
}
for(int i=0;i<arrayList.size();i++)
{
log("xxx");
log(arrayList.get(i).deviceName);
if(arrayList.get(i).deviceName.equalsIgnoreCase("Android_144b"))
{
d = arrayList.get(i);
arrayList.clear();
found = true;
break;
}
}
}
if(d!=null)
{
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = d.deviceAddress;
if(!connected)
{
mManager.connect(mChannel, config, new ActionListener()
{
#Override
public void onSuccess()
{
connected = true;
}
#Override
public void onFailure(int reason)
{
connected=false;
mManager.cancelConnect(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
Log.d("status", "success on cancelConnect()");
}
#Override
public void onFailure(int reason)
{
Log.d("status", "Fail on cancelConnect()");
}
});
}
});
}
}
}
});
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action))
{
Bundle b = intent.getExtras();
NetworkInfo info = (NetworkInfo)b.get(WifiP2pManager.EXTRA_NETWORK_INFO);
if(info.isFailover())
{
connected=false;
Log.d("status", "connection failure!");
}
else if(info.isConnected())
{
connected=true;
find.setEnabled(false);
Log.d("status", "connection is Connected!");
}
else if(info.isConnectedOrConnecting())
{
connected=false;
log("Connecting !!!");
}
else if(!info.isConnected())
{
if(connected)
{
//closeConnections();
connected=false;
}
find.setEnabled(true);
mManager.removeGroup(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
log("Success disconnect");
}
#Override
public void onFailure(int arg0)
{
log("Fail disconnect");
}
});
}
}
else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action))
{}
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
And this is the class Connection
package com.example.wifidirect;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
#SuppressLint("NewApi")
public class Connection
{
boolean found = false;
OutputStream out=null;
Socket socket = null;
boolean connected =false;
WiFiDirectBroadcastReceiver mReceiver=null;
WifiDirect instance=null;
#SuppressLint("NewApi")
Channel mChannel=null;
WifiP2pManager mManager=null;
public void sendMessage(int msg)
{
try
{
out.write(msg);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Connection(WiFiDirectBroadcastReceiver mReceiver,WifiDirect instance,Channel mChannel,WifiP2pManager mManager) throws UnknownHostException, IOException
{
this.instance=instance;
this.mReceiver=mReceiver;
this.mChannel=mChannel;
this.mManager= mManager;
socket = null;
Button send = (Button)instance.findViewById(R.id.send);
send.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try
{
log("z1");
if(socket==null)
{
log("z2");
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
log("z3");
socket= new Socket("192.168.49.1",8870);
socket.setReuseAddress(true);
log("z4");
out = socket.getOutputStream();
connected = true;
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
t.setDaemon(false);
t.start();
}
new Thread(new Runnable()
{
public void run()
{
log("trying to Send !");
while(!connected);
sendMessage(10);
log(" Data sent !");
}
}).start();
}
catch(Exception e)
{
log("exception_1");
e.printStackTrace();
log("exception_2");
log(e.getMessage());
}
}
});
}
public void closeConnections()
{
try
{
if(out!=null)
{
out.close();
out=null;
}
if(socket!=null)
{
socket.shutdownInput();
socket.shutdownOutput();
if(socket.isInputShutdown()|| socket.isOutputShutdown())
{
socket.close();
}
if(!socket.isClosed())socket.close();
}
if(socket.isConnected())
{
socket.close();
}
socket=null;
}
catch(Exception e)
{
Log.d("status", "error :( ");
e.printStackTrace();
}
}
public void connect()
{
mManager.discoverPeers(mChannel, new ActionListener()
{
#Override
public void onSuccess()
{
Log.d("status", "1");
}
#Override
public void onFailure(int reason)
{
mManager.cancelConnect(mChannel, new ActionListener() {
#Override
public void onSuccess()
{
Log.d("status", "success cancel connect");
connect();
}
#Override
public void onFailure(int reason)
{
Log.d("status", "failed cancel connect");
}
});
}
});
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
finally this is my main Activity class
package com.example.wifidirect;
import java.io.IOException;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class WifiDirect extends Activity
{
WifiP2pManager mManager;
Channel mChannel;
WiFiDirectBroadcastReceiver mReceiver;
PeerListListener listener = null;
IntentFilter mIntentFilter;
String host;
Connection con=null;
PeerListListener myPeerListListener;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi_direct);
StrictMode.enableDefaults();
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
try {
con = new Connection(mReceiver,this,mChannel,mManager);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final Button discover = (Button)findViewById(R.id.discover);
discover.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
con.connect();
}
});
}
#Override
protected void onResume()
{
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
}
#SuppressLint("NewApi")
#Override
protected void onDestroy()
{
super.onDestroy();
con.sendMessage(100);
unregisterReceiver(mReceiver);
}
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
String action = data.getAction();
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
if (mManager != null)
{
mManager.requestPeers(mChannel, myPeerListListener);
}
}
}
void log(String s)
{
Log.d("status ", s);
}
}
Just in case someone run into similar issue, I was having similar problem of seeing connection refused messages sometimes and fixed this by allowing client thread,to sleep for a second to prevent race conditions. The idea is that once two devices are connected, the ConnectionListener gets fired. After that, both server\client will launch server thread or client thread based on the role. A group owner will issue a server thread and group member will launch a client thread. Sometimes, the client thread will launch before the server thread and those fail to find a server to connect to. So, I added a one-second-sleep for the client to ensure that server thread gets registered first. Now, I don't see the problem happening. Here is my code:
private WifiP2pManager.ConnectionInfoListener connectionListener
= new WifiP2pManager.ConnectionInfoListener(){
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
// TODO Auto-generated method stub
Log.i(TAG, "onConnectionInfoAvailable");
//String groupOwnerAddress = info.groupOwnerAddress.getHostAddress();
if (info.groupFormed && info.isGroupOwner) {
// Do whatever tasks are specific to the group owner.
// One common case is creating a server thread and accepting
// incoming connections.
Log.i(TAG, "Connected as group owner...");
WifiDirectServerThread wifiDirectServerThread = new WifiDirectServerThread(context);
wifiDirectServerThread.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case,
// you'll want to create a client thread that connects to the group
// owner.
Log.i(TAG, "Connected as group member...");
Log.i(TAG, "Sleep before launching client thread to avoid race conditions...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WifiDirectClientDataThread wifiDirectClientThread = new WifiDirectClientDataThread(info.groupOwnerAddress.getHostAddress(), PORT, context);
wifiDirectClientThread.start();
}
}
};

Categories

Resources