I have an Arduino Bluetooth shield HC-05. I paired the Bluetooth shield first with Android device and tried to send data to Arduino via Bluetooth shield. Android app sends data to the shield. But Arduino not receiving the command more than (4 to 13) times I think my app not holding the connection properly with the Bluetooth shield, I am not sure about the problem. I tried with the same Arduino code with some other Android application. It was working well. So problem is in my code only. I am using log to monitor the flow of code. The data is sending from the Android device and the Bluetooth is live and still paired. I think Bluetooth shield was not receiving or it was receiving and not passing the data to Arduino. I am troubling for couple of weeks.
Thanks in Advance !!
My code goes here...
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static String address = "98:D3:31:30:25:DC";//old: 20:14:12:03:12:42, 98:D3:31:30:25:DC
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private InputStream inStream = null;
Handler handler = new Handler();
byte delimiter = 10;
boolean stopWorker = false;
int readBufferPosition = 0;
byte[] readBuffer = new byte[1024];
//
//Bluetooth sender ends
//
//
private final BroadcastReceiver commandAction = new BroadcastReceiver() {
#Override
public void onReceive(Context context2, Intent intent2) {
String com = intent2.getStringExtra("key");
commandAction(com);
Toast.makeText(context2, "commandAction:"+com, Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
commandAction("up");
}
});
GCMRegistrar.checkDevice( this );
GCMRegistrar.checkManifest( this );
final String regId = GCMRegistrar.getRegistrationId( this );
if( regId.equals( "" ) ) {
GCMRegistrar.register( this, "501396392354" );
Toast.makeText(this," 501396392354", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this,regId, Toast.LENGTH_SHORT).show();
Log.v( TAG2, "Already registered" );
Log.v(TAG2, "Registration id is: " + regId );
}
startService(new Intent(MainActivity.this, LocationService.class));
CheckBt();
Connect();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.e("Jon", device.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public Object onRetainNonConfigurationInstance() {
if (mAccessory != null) {
return mAccessory;
} else {
return super.onRetainNonConfigurationInstance();
}
}
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("in.robot.gcm.commandaction");
registerReceiver(commandAction, intentFilter);
if (mInputStream != null && mOutputStream != null) {
return;
}
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(commandAction);
closeAccessory();
}
#Override
public void onDestroy() {
unregisterReceiver(mUsbReceiver);
stopService(new Intent(MainActivity.this, LocationService.class));
try {
btSocket.close();
} catch (IOException e) {
}
super.onDestroy();
}
private void openAccessory(UsbAccessory accessory) {
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Log.d(TAG, "accessory opened");
} else {
Log.d(TAG, "accessory open fail");
}
}
private void closeAccessory() {
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
public void commandAction(String command){
byte[] buffer = new byte[1];
MediaPlayer mp;
Toast.makeText(this,"in cmd action",Toast.LENGTH_SHORT).show();
if("up".equals(command)){
buffer[0]=(byte)0;
Log.v(TAG ,"up heay");
writeData("1");
Toast.makeText(this,"UP",Toast.LENGTH_SHORT).show();
}
else if("down".equals(command)) {
buffer[0]=(byte)1;
Log.v(TAG ,"down heay");
writeData("2");
}
else if("left".equals(command)){
buffer[0]=(byte)2;
writeData("3");
}
else if("right".equals(command)){
buffer[0]=(byte)3;
writeData("4");
}
else if("break".equals(command)){
buffer[0]=(byte)4;
writeData("0");
}
else if("camera left".equals(command)){
buffer[0]=(byte)5;
//writeData("0");
}
else if("camera right".equals(command)){
buffer[0]=(byte)6;
//writeData("0");
}
else if ("jigsaw1".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw1);
mp.start();
}
else if("jigsaw2".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw2);
mp.start();
}
else if("horn".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.horn);
mp.start();
}
else if("start".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.start);
mp.start();
}
else if("ghosts".equals(command)){
mp = MediaPlayer.create(MainActivity.this, R.raw.ghosts);
mp.start();
}
else if("flash on".equals(command)){
if((this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) && !(isLighOn)){
cam = Camera.open();
Parameters params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
cam.setParameters(params);
cam.startPreview();
isLighOn=true;
Log.v("camera","flash on");
}
else{Log.v("camera","flash not exsisted");}
}
else if("flash off".equals(command)){
if(isLighOn){
cam.stopPreview();
cam.release();
isLighOn=false;
Log.v("camera","flash off");
} }
else if("location on".equals(command)){
startService(new Intent(MainActivity.this, LocationService.class));
}
else if("location off".equals(command)){
stopService(new Intent(MainActivity.this, LocationService.class));
}
else if("speed min".equals(command)){
buffer[0]=(byte)7;
}
else if("speed min".equals(command)){
buffer[0]=(byte)8;
}
else if("speed max".equals(command)){
buffer[0]=(byte)9;
}
else{
Log.v(TAG ,"no command recieved");}
if (mOutputStream != null) {
try {
mOutputStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "write failed", e);
}
}
}
//
//
//
//
private void CheckBt() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
Toast.LENGTH_SHORT).show();
}
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),
"Bluetooth null !", Toast.LENGTH_SHORT)
.show();
}
}
public void Connect() {
Log.d(TAG, address);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d(TAG, "Connecting to ... " + device);
Toast.makeText(this, "Connecting to...", Toast.LENGTH_SHORT).show();
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
Log.d(TAG, "Connection made.");
Toast.makeText(this, "Connection made Successful..", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "Unable to end the connection");
Toast.makeText(this, "Unable to end the connection", Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "Socket creation failed");
Toast.makeText(this, "connection creation failed", Toast.LENGTH_SHORT).show();
}
//beginListenForData();
}
private void writeData(String data) {
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "Bug BEFORE Sending stuff", e);
}
String message = data;
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
Toast.makeText(this, "Data Send Successful..", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.d(TAG, "Bug while sending stuff", e);
Toast.makeText(this, "Data Send Error..", Toast.LENGTH_SHORT).show();
}
}
}
Related
I am beginner and making my first project on android studio. I want to exchange a unique string between devices over Bluetooth without pairing whenever devices are near. Following is the code I tried but did not work. The code I mention is of scanning part only when click on scan it search for the device and exchange the keys but it is not working.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ON = (Button) findViewById(R.id.button3);
OFF = (Button) findViewById(R.id.button5);
Scan = (Button) findViewById(R.id.search);
myBT = BluetoothAdapter.getDefaultAdapter();
Interaction = (Button) findViewById(R.id.intr);
intentON = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
other = (TextView)findViewById(R.id.textView4);
bluelist = (ListView) findViewById(R.id.btList);
//IntView = (ListView) findViewById(R.id.InList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
pAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
bluelist.setAdapter(arrayAdapter);
random = UUID.randomUUID();
getUUID = random.toString();
code = (TextView) findViewById(R.id.textView6);
data = getIntent().getExtras().getString("SomeNumbers");
code.setText(data);
send = (String) code.getText();
checkPermission();
ON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(myBT.isEnabled())
Toast.makeText(getApplicationContext(), "Bluetooth already Enabled", Toast.LENGTH_SHORT).show();
else
bluetoothOn();
}
});
OFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetoothOff();
}
});
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
discover();
}
});
bluelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//pairDevice(device);
}
});
Interaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent getInteractions = new Intent(MainActivity.this, Interactions.class);
//Bundle args = new Bundle();
//args.putSerializable("Exposure", (Serializable)arrayList);
getInteractions.putStringArrayListExtra("Exposure", arrayList);
startActivity(getInteractions);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == BLUETOOTH_REQ_CODE) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "Bluetooth is Enabled", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Bluetooth Disabled", Toast.LENGTH_LONG).show();
}
}
}
private void discover(){
if(myBT.isDiscovering()){
myBT.cancelDiscovery();
Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show();
}
else{
if(myBT.isEnabled()) {
arrayAdapter.clear(); // clear items
myBT.startDiscovery();
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
else{
bluetoothOn();
}
}
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name to the list
arrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayAdapter.notifyDataSetChanged();
ServerClass serverClass = new ServerClass();
serverClass.start();
ClientClass clientClass = new ClientClass(pairing);
clientClass.start();
sendReceive.write(send.getBytes());
}
}
};
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(#NonNull Message msg) {
switch(msg.what)
{
case STATE_LISTENING:
Toast.makeText(getApplicationContext(), "Listening", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTING:
Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTION_FAILED:
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
break;
case STATE_MESSAGE_RECEIVED:
byte[] readBuff = (byte[]) msg.obj ;
String tempMsg = new String(readBuff,0,msg.arg1);
other.setText(tempMsg);
break;
}
return false;
}
});
private class ServerClass extends Thread
{
private BluetoothServerSocket serverSocket;
public ServerClass()
{
try {
serverSocket = myBT.listenUsingInsecureRfcommWithServiceRecord(App_Name,random);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
BluetoothSocket socket=null;
while(socket == null)
{
try {
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
socket=serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
}
if(socket != null)
{
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
sendReceive = new SendReceive(socket);
sendReceive.start();
break;
}
}
}
}
private class ClientClass extends Thread
{
private BluetoothDevice device;
private BluetoothSocket socket;
public ClientClass(BluetoothDevice device1)
{
device=device1;
try {
socket = device.createRfcommSocketToServiceRecord(random);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
try {
socket.connect();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread
{
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public SendReceive(BluetoothSocket socket)
{
bluetoothSocket=socket;
InputStream tempIn = null;
OutputStream tempOut = null;
try {
tempIn = bluetoothSocket.getInputStream();
tempOut = bluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
inputStream = tempIn;
outputStream = tempOut;
}
public void run()
{
byte[] buffer = new byte[1024];
int bytes;
while(true)
{
try {
bytes = inputStream.read(buffer);
handler.obtainMessage(STATE_MESSAGE_RECEIVED,bytes,-1,buffer).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes)
{
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I made an app which connects to bluetooth and sends and receive data in an activity. Now I have updates in the app and has to create another activities which connects to the same bluetooth device and transfer data. So I am planning to connect to bluetooth device in my second activity which has some buttons which calls for another activities. I need to retain the bluetooth connection I made in the second activity throughout the activities that are called from the second activity using buttons till the user press back button from second activity (exiting second activity). Please explain how I should change my code to make this happen. This is my current code which is used for single activity bluetooth connection.
public class ViewBoardStatus extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_board_status);
mOutStringBuffer = new StringBuffer("");
IntentFilter filter = new IntentFilter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
List<String> paireddevicesarray = new ArrayList<>();
int iNoOfPariedDev = pairedDevices.size();
int iDeviceCntr = 0;
DevAddressString = new String[iNoOfPariedDev][2];
for (BluetoothDevice device : pairedDevices)
{
DevAddressString[iDeviceCntr][0] = device.getAddress();
DevAddressString[iDeviceCntr][1] = device.getName();
iDeviceCntr++;
if (iDeviceCntr > iNoOfPariedDev)
break;
}
ArrayList<String> aList = new ArrayList<String>();
aList.add("Select Device");
for (int i = 0; i < iDeviceCntr; i++)
{
aList.add(DevAddressString[i][1]);
}
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, aList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_paireddevices.setAdapter(dataAdapter);
sp_paireddevices.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
// Object item = parentView.getItemAtPosition(position);
Log.e(TAG, "Executing On ITEM SELECTED");
int iLoc = sp_paireddevices.getSelectedItemPosition();
if (iLoc != 0)
{
Toast.makeText(getApplicationContext(), " Connecting to hardware please wait..", Toast.LENGTH_SHORT).show();
iBTDevSelcted = 1;
Log.e(TAG, "Toast message of Connecting");
address = DevAddressString[iLoc - 1][0];
Log.e(TAG, "Calling OnResume Function");
onResume();
}
else
{
Toast.makeText(getApplicationContext(), " Please select Bluetooth Device", Toast.LENGTH_SHORT).show();
}
}
public void onNothingSelected(AdapterView<?> arg0) {// do nothing
}
});
lvParaHeader.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(touchSource == null)
touchSource = v;
if(v == touchSource)
{
lvParaValue.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP)
{
clickSource = v;
touchSource = null;
}
}
return false;
}
});
lvParaValue.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(touchSource == null)
touchSource = v;
if(v == touchSource)
{
lvParaHeader.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP)
{
clickSource = v;
touchSource = null;
}
}
return false;
}
});
lvParaHeader.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(parent == clickSource) {
// Do something with the ListView was clicked
}
}
});
lvParaValue.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(parent == clickSource) {
// Do something with the ListView was clicked
}
}
});
lvParaHeader.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(view == clickSource)
lvParaValue.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
lvParaValue.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(view == clickSource)
lvParaHeader.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
sp_datatype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Log.e(l,"Starting ON Item Selected");
if (sp_paireddevices.getSelectedItemPosition()>0)
{
if (sp_datatype.getSelectedItemPosition() == 1) {
sGetRequest = sGetElectricalPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 2) {
sGetRequest = sGetGprsPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 3) {
sGetRequest = sGetSystemPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 4) {
sGetRequest = sGetRS485Para;
sendMessage(sGetRequest);
}
}
else
Toast.makeText(getApplicationContext(), " Connect to a Device and Refresh ", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
bt_Refresh.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.e(l,"Refresh Button OnClick");
if (sp_paireddevices.getSelectedItemPosition()>0)
{
if (sp_datatype.getSelectedItemPosition() == 0) {
Toast.makeText(getApplicationContext(), " Select a Parameter to Refresh ", Toast.LENGTH_SHORT).show();
}
if (sp_datatype.getSelectedItemPosition() == 1) {
sGetRequest = sGetElectricalPara;
sendMessage(sGetRequest);
Log.e(l, "Send Message Called");
}
if (sp_datatype.getSelectedItemPosition() == 2) {
sGetRequest = sGetGprsPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 3) {
sGetRequest = sGetSystemPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 4) {
sGetRequest = sGetRS485Para;
sendMessage(sGetRequest);
}
Log.e(l, "Send Message Called");
}
else
Toast.makeText(getApplicationContext(), " Connect to a Device and Refresh ", Toast.LENGTH_SHORT).show();
}
});
h = new Handler()
{
public void handleMessage(android.os.Message msg)
{
Log.e(l, "Starting Handler");
int strlen;
switch (msg.what)
{
case RECIEVE_MESSAGE:
Log.d(l, "data received = " );
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
String strMsg = new String();
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("#");
if (endOfLineIndex > 0)
{ // if end-of-line,
sJsonData = sb.substring(1, endOfLineIndex); // extract string
sb.delete(0, sb.length());
// and clear
try
{
Log.e(l, "Starting Try of Handler");
Log.e(l, "Data Received: "+sJsonData);
strlen = sJsonData.length();
Log.e(l, "String Length Obtained");
JSONObject mainobject = new JSONObject(sJsonData);
Log.e(l, "main object created");
sDataType = mainobject.getString("DATA_TYPE");
Log.e(l, "Data Type Obtained");
//tv_jsonlength.setText(String.valueOf(strlen));
//tv_JsonPara.setText(TempHeader);
iSelectedParaPostion=sp_datatype.getSelectedItemPosition();
if(sDataType.trim().equalsIgnoreCase("PARA"))
{
if(iSelectedParaPostion==1)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//tv_jsonstring.setText(sCurrentJsonData);
jsonparseelectricalpara();
}
}
if(sDataType.trim().equalsIgnoreCase("GPRS"))
{
if(iSelectedParaPostion==2)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//tv_jsonstring.setText(sCurrentJsonData);
jsonparsegprsdata();
}
}
if(sDataType.trim().equalsIgnoreCase("SYSTEM"))
{
if(iSelectedParaPostion==3)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//
// tv_jsonstring.setText(sCurrentJsonData);
jsonparseSystem();
}
}
}
catch (Exception e)
{
Log.e(l, "CATCH OF HANDLER");
}
}
break;
}
}
};
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}//oncreate
private void checkBTState()
{
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(mBluetoothAdapter==null) {
// Log.d(TAG, "error, bluetooth not supported");
} else {
if (mBluetoothAdapter.isEnabled()) {
// Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
tvconnectionstatus.setText("");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message)
{
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
{
if (Build.VERSION.SDK_INT >= 10)
{
try
{
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[]{UUID.class});
Log.e(TAG, "Bluetooth Socket Creation TRY EXECUTED");
return (BluetoothSocket) m.invoke(device, MY_UUID);
}
catch (Exception e2)
{
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.e(TAG, "Bluetooth Socket Creation CATCH EXECUTED");
}
}
Log.e(TAG, "Exiting Socket Creation Method");
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
public void onResume()
{
super.onResume();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Log.e(TAG, "Starting OnResume Method");
if (iBTDevSelcted == 0) {
Toast.makeText(getApplicationContext(), " Please select Bluetooth Device", Toast.LENGTH_SHORT).show();
return;
}
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.e(TAG, "Obtaining REMOTE DEVICE address");
try {
btSocket = createBluetoothSocket(device);
Log.e(TAG, "BT SOCKET Created");
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
mBluetoothAdapter.cancelDiscovery();
Log.e(TAG, "BT Discovery CANCELLED");
try
{
Log.e(TAG, "TRY STATEMENT OF BT CONNECTION CREATION");
btSocket.connect();
String connectedto = "Connected to: " + sp_paireddevices.getSelectedItem().toString();
tvconnectionstatus.setText(connectedto);
}
catch (IOException e)
{
Log.e(TAG, "CATCH STATEMENT OF BLUETOOTH CONNECTION CREATION");
try {
btSocket.close();
Log.e(TAG, "Bluetooth Socket Closed");
tvconnectionstatus.setText("");
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.e(TAG, "Unable to Close bluetooth connection");
}
}
// Create a data stream so we can talk to server.
// Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
Log.e(TAG, "Connection Thread Created");
mConnectedThread.start();
Log.e(TAG, "Connection Thread Started");
}
#Override
public void onPause()
{
super.onPause();
// Log.d(TAG, "...In onPause()...");
if(iBTDevSelcted==1) {
try {
btSocket.close();
tvconnectionstatus.setText("");
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
}
private class ConnectedThread extends Thread
{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket)
{
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try
{
Log.e(TAG, "Trying to get Temp Input/Output Stream");
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
Log.e(TAG, "Input/Output Stream Obtained");
}
catch (IOException e)
{
Log.e(TAG, "I/O Stream CATCH STATEMENT");
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run()
{
Log.e(TAG, "Starting RUN Method");
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true)
{
try {
Log.e(TAG, "TRY of RUN Method Started");
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
Log.e(l,"Run Executed");
Log.e(TAG, "TRY of RUN Method Completed");
} catch (IOException e)
{
Log.e(TAG, "CATCH of RUN Method");
break;
}
}
}
public void write(String s) throws IOException
{
mmOutStream.write(s.getBytes());
tvconnectionstatus.setText(s);
sGetRequest=sReset;
}
}//connectthread
private void sendMessage(String message)
{
ConnectedThread ct;
Log.e(l,"Connected Thread Object Created");
ct = mConnectedThread;
try {
ct.write(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}//class
I am creating an android application that consists of printing data from printer connected via usb. Here, I want to set page layouts such as new line printing when reached at the end of page and page borders etc. Is it possible via programatically. Please help me how to do this.
This is what i had done for printing for data:
public class DemoPrinter extends Activity {
private final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
Button create_file;
PendingIntent mPermissionIntent;
UsbManager usbManager;
UsbDevice device;
EditText print_text;
UsbDevice printer = null;
private static final int PRINTER_VENDOR_ID = 1256;
private String filename = "MySampleFile.txt";
private String filepath = "PanelFilesstorage";
File myInternalFile;
String data= "This is a sample text";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_demo_printer);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
myInternalFile = new File(directory , filename);
print_text = (EditText)findViewById(R.id.editText_printer);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
if (deviceList.size() <= 0)
{
Toast.makeText(getApplicationContext(), "Info: No device found", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "No of devices"+deviceList.size(), Toast.LENGTH_SHORT).show();
((TextView) findViewById(R.id.textView_devices))
.setText("No of device : " + deviceList.size());
}
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
int count = 0;
mPermissionIntent = PendingIntent.getBroadcast(getBaseContext(), 0,
new Intent(ACTION_USB_PERMISSION), 0);
while (deviceIterator.hasNext()) {
count++;
device = deviceIterator.next();
Log.i("info", "Device No " + count + "........");
Log.i("info", "Vendor id : " + device.getVendorId());
Log.i("info", "Product id : " + device.getProductId());
Log.i("info", "Device name : " + device.getDeviceName());
Log.i("info", "Device class : " + device.getClass().getName());
Log.i("info", "Device protocol: " + device.getDeviceProtocol());
Log.i("info", "Device subclass : " + device.getDeviceSubclass());
if (device.getVendorId() == PRINTER_VENDOR_ID) {
printer = device;
break;
}
}
findViewById(R.id.button_print).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Info", "Print command given");
IntentFilter filter = new IntentFilter(
ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
if (printer != null) {
usbManager.requestPermission(printer,
mPermissionIntent);
} else {
Log.e("Exception", "Printer not found");
}
}
});
} catch (Exception e) {
Log.e("Exception", "Exception in onCreate " + e.getMessage());
e.printStackTrace();
}
findViewById(R.id.button_create_file).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
FileOutputStream fos = new FileOutputStream(myInternalFile+"\n");
fos.write(data.toString().getBytes());
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
try {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
final UsbDevice printerDevice = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if (printerDevice != null) {
Log.i("Info", "Device permission granted");
startPrinting(printerDevice);
}
}
else
{
Log.d("Debug", "permission denied for device "
+ printerDevice);
}
}
}
} catch (Exception e)
{
Log.e("Exception", "Exception in onRecieve " + e.getMessage());
e.printStackTrace();
}
}
};
public void startPrinting(final UsbDevice printerDevice)
{
new Handler().post(new Runnable()
{
UsbDeviceConnection conn;
UsbInterface usbInterface;
#Override
public void run()
{
try
{
Log.i("Info", "Bulk transfer started");
usbInterface = printerDevice.getInterface(0);
UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = usbManager.openDevice(printer);
conn.claimInterface(usbInterface, true);
String myStringData = print_text.getText().toString();
myStringData+="\n";
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer
.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request)
{
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
// handler.sendMessage(m);
output_buffer.clear();
}
else
{
Log.i("Info", "No request recieved");
}
int transfered = conn.bulkTransfer(endPoint,
myStringData.getBytes(),
myStringData.getBytes().length, 5000);
Log.i("Info", "Amount of data transferred : " +transfered);
} catch (Exception e)
{
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
} finally
{
try
{
conn.releaseInterface(usbInterface);
Log.i("Info", "Interface released");
conn.close();
Log.i("Info", "Usb connection closed");
unregisterReceiver(mUsbReceiver);
Log.i("Info", "Brodcast reciever unregistered");
}
catch (Exception e)
{
Log.e("Exception",
"Unable to release resources because : "
+ e.getMessage());
e.printStackTrace();
}
}
}
});
}
}
I am trying to communicate from android to a microprocessor controlled device, which uses HC-05, I have tried every possible solution, but btSocket.connect() is throwing
read failed, socket might closed or timeout, read ret android
Relevant code snippet is provided below:-
/**
* Sends the data Over BlueTooth
* #param data
* bytes which is to be send to the bibox.
*
* */
private void sendDataToBlueTooth(byte[] data){
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String mMacChecking = pref.getString("BL", "bl");
if (!mMacChecking.equals("bl")) {
// Intent in = new Intent(getApplicationContext(), DataSendReceive.class);
// in.putExtra("isBtRemoteData", true);
// in.putExtra("bData", data);
// startActivity(in);
final SharedPreferences pre = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
this.mDeviceMACAddress = pre.getString("BL", "");
this.mSendArray = data;
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (this.mBluetoothAdapter == null) {
Toast.makeText(this, R.string.no_bt_device, Toast.LENGTH_LONG).show();
this.finish();
return;
}
this.connectTOdevice();
this.mHandler = new Handler() {
#SuppressLint("ShowToast")
#Override
public void handleMessage(final android.os.Message msg) {
if (msg.what == 1) {
mConnectStatus = true;
for (int i = 0; i < mSendArray.length; i++) {
write(mSendArray[i]);
}
String str = Arrays.toString(mSendArray);
Log.d("", str);
//Added an alert dialog to show the data..
// To activate the alert, put the below 3 lines inside the on click of the OK button...
onBackPressed();
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
} else if (msg.what == 2) {
// Set button to display current status
// connectStat = true;
final byte[] readBuf = (byte[]) msg.obj;
System.out.println("InHandler - ");
String receivedString = "";
for (final byte b : readBuf) {
// `byte` to `Byte`
final int temp = b;
final String tempString = String.valueOf(temp);
receivedString = receivedString.concat("," + tempString);
}
Log.d("received string", receivedString);
for (final byte element : readBuf) {
System.out.print(element + ",");
}
// System.out.println("" + readBuf);
} else if (mBluetoothAdapter.isEnabled()) {
final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
// Connection failed
mFailToast.show();
/* Intent scan = new Intent(getApplicationContext(), BluetoothDeviceDiscover.class); */
finish();
// startActivity(scan);
}
}
};
mFailToast = Toast.makeText(this, "Failed to connect please on " + this.mDeviceMACAddress + " or scan for new device", Toast.LENGTH_SHORT);
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (this.mBluetoothAdapter == null) {
Toast.makeText(this, R.string.no_bt_device, Toast.LENGTH_LONG).show();
this.finish();
return;
}
this.connectTOdevice();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (this.mBtSocket != null) {
this.mBtSocket.close();
}
} catch (final IOException e2) {}
}
public void write(final byte arr2) {
if (this.mConnectStatus == true) if (this.mOutStream != null) {
try {
this.mOutStream.write(arr2);
} catch (final IOException e) {
showToast(getString(R.string.dataNotSendMessage), false);
}
} else {
showToast(getString(R.string.switchOnBlueToothDevice), false);
}
}
public void connectTOdevice() {
this.mConnectThread = new ConnectThread(this.mDeviceMACAddress);
this.mConnectThread.start();
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
boolean isUnpairToastToBeDisplayed = true;
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String DEVICE_PIN = getString(R.string.device_pin);
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals("android.bluetooth.device.action.BOND_STATE_CHANGED")) {
byte[] pin;
try {
pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class).invoke(BluetoothDevice.class, DEVICE_PIN);
BluetoothDevice.class.getMethod("setPin", byte[].class).invoke(device, pin);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
//Continue work here....
//If the number of paired devices greater than 3, unpair everything except the current one...
//Causing problem in lenovo tablet...
//Problem :- Tablet hang for more than 4 paired devices...
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices;
mPairedDevices = btAdapter.getBondedDevices();
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String deviceAddress = pref.getString("BL", "NoDevice");
if (mPairedDevices.size() > MAX_ALLOWED_PAIRED_DEVICES) {
// findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (final BluetoothDevice deviceForLoop : mPairedDevices) {
//if the device for loop doesn't match the latest saved address...
//unpair the device...
if(!deviceAddress.equals(deviceForLoop.getAddress())){
isUnpairToastToBeDisplayed = false;
unpairDevice(deviceForLoop);
isUnpairToastToBeDisplayed = true;
}
}
}
showToast(getString(R.string.pairedToastMessage),false);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
if(!isUnpairToastToBeDisplayed)
showToast(getString(R.string.unpairedToastMessage),false);
}
}
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
Intent i = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(i);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
}
};
private void unpairDevice(final BluetoothDevice device) {
try {
final Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (final Exception e) {
// Log.e(TAG, e.getMessage());
}
}
public class ConnectThread extends Thread {
private final String address;
private boolean connectionStatus;
ConnectThread(final String MACaddress) {
this.address = MACaddress;
this.connectionStatus = false;
}
#Override
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(this.address);
IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairReceiver, intent);
try {
SPP_UUID = device.getUuids()[0].getUuid();
BluetoothSocket tmp = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
Class<?> clazz = tmp.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[] {Integer.valueOf(1)};
mBtSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
} catch (final IOException e) {
this.connectionStatus = false;
} catch (Exception e) {
}
} catch (final IllegalArgumentException e) {
this.connectionStatus = false;
}
try {
mBtSocket.connect();
this.connectionStatus = true;
} catch (final IOException e1) {
try {
mBtSocket.close();
Log.d("check", "check");
} catch (final IOException e2) {}
}
// Create a data stream so we can talk to server.
try {
mOutStream = mBtSocket.getOutputStream();
} catch (final IOException e2) {
this.connectionStatus = false;
}
// Send final result
if (this.connectionStatus) {
mHandler.sendEmptyMessage(1);
} else {
mHandler.sendEmptyMessage(0);
}
}
}
}
I found the answer in the following question:-
IOException: read failed, socket might closed - Bluetooth on Android 4.3
Actually I had to use reflection only on the fall back, ie, inside the catch when the connect fails.
I want to print the text file from my application in android 8 through Bluetooth or WiFi. Please suggest me the solution.
this is a sample
package com.example.untitled2;
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.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MyActivity extends Activity {
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(MyActivity.this, "no device", Toast.LENGTH_LONG).show();
}
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
Set<BluetoothDevice> bluetoothDevices = mBluetoothAdapter.getBondedDevices();
if (bluetoothDevices.size() == 0)
return;
OutputStream mmOutStream;
BluetoothDevice device = bluetoothDevices.iterator().next();
try {
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
mmOutStream = socket.getOutputStream();
/*String textPrint = ""+(char) 27 + (char)116 + (char) 27;*/
String textPrint = "this is example text"+(char)10;
mmOutStream.flush();
mmOutStream.write(textPrint.getBytes());
mmOutStream.flush();
for (int i = 0; i < 10; i++) {
mmOutStream.write(textPrint.getBytes());
}
mmOutStream.flush();
//mmOutStream.wait();
mmOutStream.close();
socket.close();
} catch (IOException e) {
Toast.makeText(MyActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
Here is my code [found online & modified as per my reqt] to connect to a Blue-tooth printer, works perfectly... tried n tested. :-)
package com.nvsoft.s2pay.mmsl.bluetoothprinter;
import android.app.Activity;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import com.nvsoft.s2pay.sms.DynaCCSmsServiceConstants;
import com.nvsoft.s2pay.util.StringUtil;
import java.util.HashSet;
import org.json.me.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//This class is meant for wrapping the Bluetooth connecting interface provided by android devices.......
//Basically is a state machine, and the communications will happen in a separate thread so as not to obstruct the main UI
public class BTWrapperActivity extends Activity {
public static final int REQUEST_CONNECT_BT = 0x2300;//8960
public static final int REQUEST_ENABLE_BT = 0x1000;//4096
public static final String DEVICES_DISCOVERED = "DD";
public static final String EXTRA_DEVICE_ADDRESS = DynaCCSmsServiceConstants.PRINTER_MAC_ADDRESS;
private static final String ERROR = "ecode";
private static final String ERROR_MSG = "emsg";
public static int ERROR_CODE = 0;
int request;
static private BluetoothAdapter mBluetoothAdapter = null;
static private Set<BluetoothDevice> btDevices = null;
String deviceNames = null;
JSONObject jobj = new JSONObject();
Intent parentIntent = null;
BluetoothDevice selectedDevice = null;
static private BluetoothSocket mbtSocket = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
deviceNames = bundle.getString(EXTRA_DEVICE_ADDRESS);
parentIntent = getIntent();
request = bundle.getInt(BluetoothFilePrinter.REQUEST_CODE);
try {
if (request != DynaCCSmsServiceConstants.EXIT_ACTIVITY_REQUEST){
if (initDevicesList() != 0) {
this.finish();
return;
}
}
} catch (Exception ex) {
getIntent().putExtra(ERROR, 701);
getIntent().putExtra(ERROR_MSG, ex.getMessage());
finish();
return;
}
// Register the Broadcast receiver for handling new BT device discovery
//IntentFilter btIntentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//this.registerReceiver(mBTReceiver, new IntentFilter(DynaCCSmsServiceConstants.ACTION_EXIT_ACTIVITY));
this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED));
this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
this.registerReceiver(mBTReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
this.registerReceiver(mBTReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
if (request == DynaCCSmsServiceConstants.EXIT_ACTIVITY_REQUEST) {
unregisterReceiver(mBTReceiver);
this.finish();
}
}
public static BluetoothSocket getSocket() {
return mbtSocket;
}
private void flushData() {
try {
/*if (mbtSocket != null) {
mbtSocket.close();
mbtSocket = null;
}*/
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
if (btDevices != null) {
btDevices.clear();
btDevices = null;
}
if (deviceNames!=null) {
deviceNames = null;
}
finalize();
} catch(Exception ex){
getIntent().putExtra(ERROR, 702);
getIntent().putExtra(ERROR_MSG, ex.getMessage());
} catch (Throwable e) {
getIntent().putExtra(ERROR, 702);
getIntent().putExtra(ERROR_MSG, e.getMessage());
}
}
// This method will Connect to our SPP Bluetooth Device after discovering and pairing if required
// Do not forget to add the permission for Bluetooth to use this method
// Also this method is very tightly coupled with the above method, for getting the status of bt connection
private int initDevicesList() {
// Flush any Pending Data to rediscover devices
if (request == DynaCCSmsServiceConstants.DISCOVER_REQUEST) {
flushData();
}
// Get the Bluetooth Adaptor of the device
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
return -1;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// ENABLE BLUETOOTH on DEVICE if not ALREADY TURNED ON
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
try {
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} catch (Exception ex) {
return -2;
}
return 0;
} // End getDeviceList
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent intent) {
super.onActivityResult(reqCode, resultCode, intent);
if (intent == null) {
intent = getIntent();
}
switch (reqCode) {
case REQUEST_ENABLE_BT:
if (request == DynaCCSmsServiceConstants.DISCOVER_REQUEST) {
if (resultCode == RESULT_OK) {
// Start getting the paired devices list
Set<BluetoothDevice> btDeviceList = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
try {
if (btDeviceList.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : btDeviceList) {
jobj.put(device.getName(), device.getAddress());
if (btDeviceList.contains(device) == false) {
btDevices.add(device); // Add the device to the device list
jobj.put(device.getName(), device.getAddress());
}
}
if (jobj != null) {
intent.putExtra(DEVICES_DISCOVERED, jobj.toString());
}
setResult(Activity.RESULT_OK, intent);
finish();
} else {
mBluetoothAdapter.startDiscovery();
}
} catch (Exception ex) {
getIntent().putExtra(ERROR, 704);
getIntent().putExtra(ERROR_MSG, ex.getMessage());
setResult(Activity.RESULT_CANCELED, intent);
}
} else {
getIntent().putExtra(ERROR, 704);
getIntent().putExtra(ERROR_MSG, "Permission to enable Bluetooth on the device was denied. Please enable Bluetooth and retry.");
setResult(Activity.RESULT_CANCELED, intent);
finish();
}
}//end of discovery
else if (request == DynaCCSmsServiceConstants.CONNECT_REQUEST || request == DynaCCSmsServiceConstants.PRINT_REQUEST) {
if (resultCode == RESULT_OK) {
if (deviceNames!=null) {
connect(deviceNames);
}else{
getIntent().putExtra(ERROR, 704);
getIntent().putExtra(ERROR_MSG, "Could not find any printer.");
setResult(Activity.RESULT_CANCELED, intent);
finish();
}
}else{
getIntent().putExtra(ERROR, 704);
getIntent().putExtra(ERROR_MSG, "Permission to enable Bluetooth on the device was denied. Please enable Bluetooth and retry.");
setResult(Activity.RESULT_CANCELED, intent);
finish();
}
}
break;
case REQUEST_CONNECT_BT:
if (resultCode == Activity.RESULT_OK) {
setResult(Activity.RESULT_OK, intent);
} else {
setResult(Activity.RESULT_CANCELED, intent);
}
finish();
break;
}
}
private final BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Get the BluetoothDevice object from the Intent
BluetoothDevice device ;
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
// No paired device found
if (btDevices == null) {
btDevices = new HashSet<BluetoothDevice>();
btDevices.add(device);
jobj.put(device.getName(), device.getAddress());
} else {
if (!btDevices.contains(device)) {
btDevices.add(device);
jobj.put(device.getName(), device.getAddress());
}
}
intent.putExtra(DEVICES_DISCOVERED, jobj.toString());
} catch (Exception ex) {
getIntent().putExtra(ERROR, 705);
getIntent().putExtra(ERROR_MSG, ex.getMessage());
}
} else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
intent.putExtra("IS_CONNECTED", true);
} else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//#ifndef REMOVE_DEBUG
logger.debug("BTWrapperActivity - ", " Device is about to disconnect");
//#endif
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//#ifndef REMOVE_DEBUG
logger.debug("BTWrapperActivity - ", "Device has disconnected");
//#endif
intent.putExtra("IS_CONNECTED", false);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//#ifndef REMOVE_DEBUG
logger.debug("BTWrapperActivity - ", "DISCOVERY FINISSHED");
//#endif
if (request == DynaCCSmsServiceConstants.DISCOVER_REQUEST) {
intent.putExtra(DEVICES_DISCOVERED, jobj.toString());
sendDiscoveryResult(intent);
}
}else if(Intent.ACTION_SCREEN_ON.equals(action)){
//#ifndef REMOVE_DEBUG
logger.debug("BTWrapperActivity - ", "SCREEN ON");
//#endif
}else if(Intent.ACTION_SCREEN_OFF.equals(action)){
//#ifndef REMOVE_DEBUG
logger.debug("BTWrapperActivity - ", "SCREEN OFF");
//#endif
}
}
};
private void connect(final String deviceAddress) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
return;
} else {
selectedDevice = mBluetoothAdapter.getRemoteDevice(deviceAddress);
}
// Cancel the dicovery if still going on
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
if (mbtSocket != null) {
try {
mbtSocket.close();
} catch (IOException ex) {
getIntent().putExtra(ERROR, 706);
getIntent().putExtra(ERROR_MSG, ex.getMessage());
setResult(Activity.RESULT_CANCELED, getIntent());
finish();
}
mbtSocket = null;
}
// Try to connect with the selected device,
// made the thread different as the connecting proceedure might break down the system
Thread connectThread = new Thread(new Runnable() {
#Override
public void run() {
Intent intent = getIntent();
String errMsg = "";
try {
try {
Method m = selectedDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class});
try {
mbtSocket = (BluetoothSocket) m.invoke(selectedDevice, 1);
} catch (IllegalArgumentException e) {
errMsg = e.getMessage();
getIntent().putExtra(ERROR, 707);
getIntent().putExtra(ERROR_MSG, errMsg);
} catch (IllegalAccessException e) {
errMsg = e.getMessage();
getIntent().putExtra(ERROR, 708);
getIntent().putExtra(ERROR_MSG, errMsg);
} catch (InvocationTargetException e) {
errMsg = e.getMessage();
getIntent().putExtra(ERROR, 709);
getIntent().putExtra(ERROR_MSG, errMsg);
}finally{
if (!StringUtil.isEmpty(errMsg) && intent.getExtras().getInt(ERROR)>0) {
setResult(Activity.RESULT_CANCELED, getIntent());
finish();
}
}
} catch (SecurityException e) {
errMsg = e.getMessage();
getIntent().putExtra(ERROR, 710);
getIntent().putExtra(ERROR_MSG, errMsg);
setResult(Activity.RESULT_CANCELED, getIntent());
finish();
} catch (NoSuchMethodException e) {
errMsg = e.getMessage();
getIntent().putExtra(ERROR, 711);
getIntent().putExtra(ERROR_MSG, errMsg);
setResult(Activity.RESULT_CANCELED, getIntent());
finish();
}
//mbtSocket =
selectedDevice.createRfcommSocketToServiceRecord(SPP_UUID);
ERROR_CODE = intent.getExtras().getInt(ERROR);
//#ifndef REMOVE_DEBUG
logger.debug("ERROR = ", ERROR_CODE);
//#endif
if (ERROR_CODE == 0) {
mbtSocket.connect();
//#ifndef REMOVE_DEBUG
logger.debug("##BTWrapperActivity - ", "Connected to selectedDevice = " + (String) intent.getExtras().get(EXTRA_DEVICE_ADDRESS));
//#endif
intent.putExtra("IS_CONNECTED", true);
setResult(Activity.RESULT_OK, intent);
} else {
intent.putExtra(ERROR, ERROR_CODE);
intent.putExtra(ERROR_MSG,errMsg);
setResult(Activity.RESULT_CANCELED, intent);
finish();
}
} catch (IOException ex) {
getIntent().putExtra(ERROR, 712);
getIntent().putExtra(ERROR_MSG, "Unable to Connect to the Printer. Please verify the printer settings and try again.");
getIntent().putExtra("IS_CONNECTED", false);
ex.printStackTrace();
setResult(Activity.RESULT_CANCELED, intent);
finish();
}finally{
finish();
}
}
});
connectThread.start();
}
private Runnable socketErrorRunnable = new Runnable() {
#Override
public void run() {
getIntent().putExtra(ERROR, 714);
getIntent().putExtra(ERROR_MSG,"Cannot establish connection");
mBluetoothAdapter.startDiscovery();
}
};
protected void onStop() {
unregisterReceiver(mBTReceiver);
super.onStop();
}
private void sendDiscoveryResult(Intent mIntent){
mIntent.putExtra(DEVICES_DISCOVERED, jobj.toString());
setResult(Activity.RESULT_OK, mIntent);
finish();
}
private String getDisplayMessage(){
String message = "Please Wait!!";
switch(request) {
case DynaCCSmsServiceConstants.DISCOVER_REQUEST :
message = "Discovery in progress!!";
break;
case DynaCCSmsServiceConstants.CONNECT_REQUEST:
message = "Connecting...Please Wait!!";
break;
case DynaCCSmsServiceConstants.PRINT_REQUEST:
message = "Printing in progress!!";
break;
}
return message;
}} // End of class definition