My app is run succeed but has some fatal errors - android

I want to try basic bluetooth chat aplication. This is my code. I have Listen,List view and send buttons.
Listen: searching bluetooth devices
List view: Show the devices list
Send: send message
If I press the listen button. There is no problem but if I press list view or send button I have fatal errors and closing my app.
package com.example.duygu.btsendmessage;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
Button listen, btsend, listdevice;
ListView listview;
TextView textview, messageview;
EditText entermessage;
BluetoothAdapter myBluetoothAdapter;
BluetoothDevice[] btArray;
Intent enableIntent;
SendReceive sendReceive;
ArrayList<String> stringArrayList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
static final int STATE_LISTENING = 1;
static final int STATE_CONNECTING = 2;
static final int STATE_CONNECTED = 3;
static final int STATE_CONNECTION_FAILED = 4;
static final int STATE_MESSAGE_RECEIVER = 5;
int REQUEST_ENABLE_BLUETOOTH = 1;
private static final String APP_NAME = "BTCom";
private static final UUID MYUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
findviewbyidset();
if (!myBluetoothAdapter.isEnabled()) {
enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}
implementListeners();
}
private void findviewbyidset() {
listen = (Button) findViewById(R.id.listen);
btsend = (Button) findViewById(R.id.btsend);
listdevice = (Button) findViewById(R.id.listdevice);
listview = (ListView) findViewById(R.id.listview);
textview = (TextView) findViewById(R.id.textview);
messageview = (TextView) findViewById(R.id.messageview);
entermessage = (EditText) findViewById(R.id.entermessage);
}
private void implementListeners() {
listdevice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Set<BluetoothDevice> bt = myBluetoothAdapter.getBondedDevices();
String[] strings = new String[bt.size()];
//btArray=new BluetoothDevice[bt.size()];
int index = 0;
if (bt.size() > 0) {
for (BluetoothDevice device : bt) {
strings[index] = device.getName();
index++;
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, strings);
listview.setAdapter(arrayAdapter);
}
}
});
listen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ServerClass serverClass=new ServerClass();
serverClass.start();
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ClientClass clientClass= new ClientClass(btArray[i]);
clientClass.start();
textview.setText("Connecting");
}
});
btsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String string= String.valueOf(entermessage.getText());
sendReceive.write(string.getBytes());
}
});
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case STATE_LISTENING:
textview.setText("Listening");
break;
case STATE_CONNECTING:
textview.setText("Connecting");
break;
case STATE_CONNECTED:
textview.setText("Connected");
break;
case STATE_CONNECTION_FAILED:
textview.setText("Connection Failed");
break;
case STATE_MESSAGE_RECEIVER:
byte[] readBuff= (byte[]) msg.obj;
String tempMsg=new String(readBuff,0,msg.arg1);
messageview.setText(tempMsg);
break;
}
return true;
}
});
private class ServerClass extends Thread {
private BluetoothServerSocket serverSocket;
public ServerClass() {
try {
serverSocket = myBluetoothAdapter.listenUsingRfcommWithServiceRecord(APP_NAME, MYUUID);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
BluetoothSocket socket=null;
while(socket==null){
try{
Message message=Message.obtain();
message.what=STATE_CONNECTING;
handler.sendMessage(message);
socket=serverSocket.accept();
}
catch(IOException e){
e.printStackTrace();
Message message=Message.obtain();
message.what=STATE_CONNECTING;
handler.sendMessage(message);
}
if(socket!=null){
Message message=Message.obtain();
message.what=STATE_CONNECTED;
handler.sendMessage(message);
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(MYUUID);
} catch(IOException e){
e.printStackTrace();
}
}
public void run(){
try{
socket.connect();
Message message=Message.obtain();
message.what=STATE_CONNECTED;
handler.sendMessage(message);
sendReceive=new SendReceive(socket);
sendReceive.start();
}
catch(IOException e){
e.printStackTrace();
Message message=Message.obtain();
message.what=STATE_CONNECTION_FAILED;
handler.sendMessage(message);
}
}
}
private class SendReceive extends Thread{
private BluetoothSocket bluetoothSocket;
private InputStream inputStream;
private 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();
}
}
public void run(){
byte[] buffer=new byte[1024];
int bytes;
while(true){
try {
bytes=inputStream.read(buffer);
handler.obtainMessage(STATE_MESSAGE_RECEIVER,bytes,-1,buffer).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And my Fattal Erorrs:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.duygu.btsendmessage, PID: 7917
java.lang.NullPointerException: Attempt to read from null array
at com.example.duygu.btsendmessage.MainActivity$3.onItemClick(MainActivity.java:125)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
at android.widget.AbsListView.performItemClick(AbsListView.java:1188)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3100)
at android.widget.AbsListView$3.run(AbsListView.java:4091)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5525)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Edit 1
I changed this part of code and fixed the list view button but send button has some erorr.
private void implementListeners() {
listdevice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Set<BluetoothDevice> bt = myBluetoothAdapter.getBondedDevices();
String[] strings = new String[bt.size()];
btArray=new BluetoothDevice[bt.size()];
int index = 0;
if (bt.size() > 0) {
for (BluetoothDevice device : bt) {
btArray[index] = device;
strings[index] = device.getName();
index++;
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, strings);
listview.setAdapter(arrayAdapter);
}
}
});
Fatal error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.duygu.btsendmessage, PID: 16656
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.duygu.btsendmessage.MainActivity$SendReceive.write(byte[])' on a null object reference
at com.example.duygu.btsendmessage.MainActivity$4.onClick(MainActivity.java:135)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21215)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5525)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Edit 2
I changed all of search code.
package com.example.duygu.btsendmessage;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
Button listen, btsend, listdevice;
ListView listview;
TextView textview, messageview;
EditText entermessage;
BluetoothAdapter myBluetoothAdapter;
BluetoothDevice[] btArray;
Intent enableIntent;
SendReceive sendReceive;
static final int STATE_LISTENING = 1;
static final int STATE_CONNECTING = 2;
static final int STATE_CONNECTED = 3;
static final int STATE_CONNECTION_FAILED = 4;
static final int STATE_MESSAGE_RECEIVER = 5;
int REQUEST_ENABLE_BLUETOOTH = 1;
private static final String APP_NAME = "BTCom";
private static final UUID MYUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
ArrayList<String> stringArrayList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(myReceiver,intentFilter);
findviewbyidset();
int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
implementListeners();
}
private void findviewbyidset() {
listen = (Button) findViewById(R.id.listen);
btsend = (Button) findViewById(R.id.btsend);
listdevice = (Button) findViewById(R.id.listdevice);
listview = (ListView) findViewById(R.id.listview);
textview = (TextView) findViewById(R.id.textview);
messageview = (TextView) findViewById(R.id.messageview);
entermessage = (EditText) findViewById(R.id.entermessage);
}
private void implementListeners() {
listdevice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myBluetoothAdapter.startDiscovery();
if (!myBluetoothAdapter.isEnabled()) {
enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}
/* Set<BluetoothDevice> bt = myBluetoothAdapter.getBondedDevices();
String[] strings = new String[bt.size()];
btArray=new BluetoothDevice[bt.size()];
int index = 0;
if (bt.size() > 0) {
for (BluetoothDevice device : bt) {
btArray[index] = device;
strings[index] = device.getName();
index++;
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, strings);
listview.setAdapter(arrayAdapter);
}*/
}
});
listen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ServerClass serverClass=new ServerClass();
serverClass.start();
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ClientClass clientClass= new ClientClass(device);
clientClass.start();
textview.setText("Connecting");
}
});
btsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String string= String.valueOf(entermessage.getText());
sendReceive.write(string.getBytes());
}
});
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case STATE_LISTENING:
textview.setText("Listening");
break;
case STATE_CONNECTING:
textview.setText("Connecting");
break;
case STATE_CONNECTED:
textview.setText("Connected");
break;
case STATE_CONNECTION_FAILED:
textview.setText("Failed");
break;
case STATE_MESSAGE_RECEIVER:
byte[] readBuff= (byte[]) msg.obj;
String tempMsg=new String(readBuff,0,msg.arg1);
messageview.setText(tempMsg);
break;
}
return true;
}
});
private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
stringArrayList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
listview.setAdapter(new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, stringArrayList));
}
}
};
private class ServerClass extends Thread {
private BluetoothServerSocket serverSocket;
public ServerClass() {
try {
serverSocket = myBluetoothAdapter.listenUsingRfcommWithServiceRecord(APP_NAME, MYUUID);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
BluetoothSocket socket=null;
while(socket==null){
try{
Message message=Message.obtain();
message.what=STATE_CONNECTING;
handler.sendMessage(message);
socket=serverSocket.accept();
}
catch(IOException e){
e.printStackTrace();
Message message=Message.obtain();
message.what=STATE_CONNECTING;
handler.sendMessage(message);
}
if(socket!=null){
Message message=Message.obtain();
message.what=STATE_CONNECTED;
handler.sendMessage(message);
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(MYUUID);
} catch(IOException e){
e.printStackTrace();
}
}
public void run(){
try{
socket.connect();
Message message=Message.obtain();
message.what=STATE_CONNECTED;
handler.sendMessage(message);
sendReceive=new SendReceive(socket);
sendReceive.start();
}
catch(IOException e){
e.printStackTrace();
Message message=Message.obtain();
message.what=STATE_CONNECTION_FAILED;
handler.sendMessage(message);
}
}
}
private class SendReceive extends Thread{
private BluetoothSocket bluetoothSocket;
private InputStream inputStream;
private 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();
}
}
public void run(){
byte[] buffer=new byte[1024];
int bytes;
while(true){
try {
bytes=inputStream.read(buffer);
handler.obtainMessage(STATE_MESSAGE_RECEIVER,bytes,-1,buffer).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
How can I change this code:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ClientClass clientClass= new ClientClass(**????**);
clientClass.start();
textview.setText("Connecting");
}
});

You are sending an empty String array to ArrayAdapter constructor in implementListeners() function.
Change the setOnClickListerner to below
private void implementListeners() {
listdevice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Set<BluetoothDevice> bt = myBluetoothAdapter.getBondedDevices();
String[] strings = new String[bt.size()];
btArray=new BluetoothDevice[bt.size()];
int index = 0;
if (bt.size() > 0) {
for (BluetoothDevice device : bt) {
btArray[index] = device;
strings[index] = bt.getName();
index++;
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, strings);
listview.setAdapter(arrayAdapter);
}
}
});
Answer to Edit 2
Declare an ArrayList of BluetoothDevice
ArrayList<BluetoothDevice> list = new ArrayList<>();
Add this list.add(device); in
private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
list.add(device); // this line here
stringArrayList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
listview.setAdapter(new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, stringArrayList));
}
}
};
and finally change listview.setOnItemClickListener to
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ClientClass clientClass= new ClientClass(list.get(i));
clientClass.start();
textview.setText("Connecting");
}
});

Related

Send Video file from Android to Arduino

From the below code I can convert a image file to byte array in my mobile app.But I cannot Convert a video file since OutOfMemoryError exception comes. I want to send a video file to a arduino board. Since I can send a string from android app to arduino, I am trying to send a video file like that. But it fails. I there any other solution to solve my problem?please help.
Code for converting image to byte array
package com.example.krishan.detectusbplugin;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file = new File(Environment.getExternalStorageDirectory() + "/Output/" +"My.mp4");
// convertFileToByteArray(file);
System.out.println(Arrays.toString(convertFileToByteArray(file)));
try {
System.out.write(convertFileToByteArray(file));
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 8];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return byteArray;
}
}
Code for sending a string to arduino through usb cable
package com.hariharan.arduinousb;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
public final String ACTION_USB_PERMISSION = "com.hariharan.arduinousb.USB_PERMISSION";
Button startButton, sendButton, clearButton, stopButton;
TextView textView;
EditText editText;
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serialPort;
UsbDeviceConnection connection;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
tvAppend(textView, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the Serial connection.
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { //Set Serial Connection Parameters.
setUiEnabled(true);
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
tvAppend(textView, "Serial Connection Opened!\n");
} else {
Log.d("SERIAL", "PORT NOT OPEN");
Toast.makeText(getApplicationContext(), "SERIAL , PORT NOT OPEN", Toast.LENGTH_LONG).show();
}
} else {
Log.d("SERIAL", "PORT IS NULLPORT IS NULL");
Toast.makeText(getApplicationContext(), "SERIAL , PORT IS NULL", Toast.LENGTH_LONG).show();
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED");
Toast.makeText(getApplicationContext(), "SERIAL , PERM NOT GRANTED", Toast.LENGTH_LONG).show();
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onClickStart(startButton);
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
onClickStop(stopButton);
}
}
;
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
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);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(broadcastReceiver, filter);
}
public void setUiEnabled(boolean bool) {
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public void onClickStart(View view) {
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int devicePID = device.getProductId();
if (devicePID == 0x0043)//Arduino Product ID in Hexa
{
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, pi);
keep = false;
} else {
Toast.makeText(getApplicationContext(), "PID does not match", Toast.LENGTH_LONG).show();
connection = null;
device = null;
}
if (!keep)
break;
}
}
}
public void onClickSend(View view) {
String string = editText.getText().toString();
serialPort.write(string.getBytes());
tvAppend(textView, "\nData Sent : " + string + "\n");
}
public void onClickStop(View view) {
setUiEnabled(false);
serialPort.close();
tvAppend(textView, "\nSerial Connection Closed! \n");
}
public void onClickClear(View view) {
textView.setText(" ");
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}
}

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.

send and receive string with bluetooth in 2 android devices

hi guys i am trying to send string from one phone to anther .
1) from one phone(client) i am clicking the paired listview to connect with the anther device(ConnectThread).
2) the second phone which is the server alerts that he has been connected with the device in step 1(AcceptThread).
3) after he get connected he start a new managerconnection thread and send along a string(in AcceptThread after connecting is sucessfull it starts a new managerConnection thread .
4) the other phone(after been connected to server it starts a new managerConnecting thread) should get the bytes from function read and put in the log how much bytes he read it seems its not getting any bytes at all can someone tell me what should i changed in my code?
package com.example.barhom.waves;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BlueToothServerActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private static final String TAG = "buckysmessage";
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private TextView serverStatus;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private AcceptThread mSecureAcceptThread;
private manageConnectedSocket manager ;
// Unique UUID for this application
private static final UUID MY_UUID =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME_SECURE = "waves";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_server);
serverStatus = (TextView) findViewById(R.id.serverStatus);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
onBtn = (Button)findViewById(R.id.turnOn);
onBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),"Listview clicked" ,
Toast.LENGTH_LONG).show();
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
#Override
protected void onResume() {
super.onResume();
// setting the device to listen for connections(bluetooth)
AcceptThread mSecureAcceptThread= new AcceptThread();
mSecureAcceptThread.start();
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
private boolean running = true;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
serverStatus.setText("Server Status: Listing for connection");
Log.d(TAG, "SERVER IS LISING FOR CONNECTIONS");
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = myBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID);
} catch (IOException e) {running = false; }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (running) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
manager=new manageConnectedSocket(socket);
manager.start();
try {
mmServerSocket.close();
Log.d(TAG, "SERVER IS CONNECTED");
String blahblah="asdasds";
manager.write(blahblah.getBytes());
break;
}catch (IOException e) {
break;
}
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
private class manageConnectedSocket extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public manageConnectedSocket(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
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 {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
Log.d(TAG,"WROTE A STRING TO ANTHER PHONE");
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
and the code for the client(the second phone):
package com.example.barhom.waves;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
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.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BlueToothClientActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
private static final String TAG = "buckysmessage";
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private TextView serverStatus;
private ConnectThread mConnectThread;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private manageConnectedSocket manager ;
// Unique UUID for this application
private static final UUID MY_UUID =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME_SECURE = "waves";
private BluetoothDevice device;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_client);
serverStatus = (TextView) findViewById(R.id.serverStatus);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(), "Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
onBtn = (Button)findViewById(R.id.turnOn);
onBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Toast.makeText(getApplicationContext(),"adress is"+address,
Toast.LENGTH_LONG).show();
device = myBluetoothAdapter.getRemoteDevice(address);
ConnectThread mConnectThread=new ConnectThread(device );
mConnectThread.start();
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
#Override
protected void onResume() {
super.onResume();
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(), "Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
myBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
manager=new manageConnectedSocket(mmSocket);
manager.start();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
// manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class manageConnectedSocket extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public manageConnectedSocket(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
int read = -1;
final byte[] bytes = new byte[2048];
for (; (read = mmInStream.read(bytes)) > -1;) {
final int count = read;
Log.d(TAG,"String size is"+count);
}
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
any help will be great!
thanks.

Android/Java BluetoothSocket InputStream won't read data

I am implementing a simple app that sends and receives data between two devices via bluetooth.
I am following the android developer's blog's bluetoothchat example, but my application seems unable to read from the inputstream of a socket.
Writing to the socket is fine. The app does not throw an error nor update the textview as it is supposed to. Any help would be appreciated. Thank you!
Main activity.java(where list of devices are shown and selected) - probably not the errored file:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.*;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends ActionBarActivity {
private final static int REQUEST_ENABLE_BT = 22;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME = "Bluetooth!";
ListView listView;
ArrayList<BluetoothDevice> deviceList;
ArrayAdapter<String> arrayAdapter;
ScanReciever reciever;
BluetoothAdapter bluetooth_adapter;
Button onButton;
Button scanButton;
Button alreadyButton;
AcceptThread acceptThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceList = new ArrayList<>();
//arrayAdapter = new ArrayAdapter<>(this, R.xml.table_item, android.R.id.text1, deviceList);
arrayAdapter = new ArrayAdapter<String>(this, R.layout.table_item);
// Set up Buttons
onButton = (Button) findViewById(R.id.onButton);
scanButton = (Button) findViewById(R.id.scanButton);
onButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
askAdapterOn();
}
});
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanForDevices();
}
});
// Set up listview
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
callButtons(deviceList.get(position));
}
});
// Bluetooth setup.
bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
// If device is incapable of using bluetooth:
if (bluetooth_adapter == null) {
onButton.setEnabled(false);
scanButton.setEnabled(false);
}
else if (!bluetooth_adapter.isEnabled()) { // If bluetooth is off:
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
onButton.setEnabled(true);
scanButton.setEnabled(false);
}
else { // Bluetooth is on and ready:
onButton.setEnabled(false);
scanButton.setEnabled(true);
alreadyButton = (Button) findViewById(R.id.alreadyButton);
alreadyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Collect current devices into a set.
Set<BluetoothDevice> pairedDevices = bluetooth_adapter.getBondedDevices();
// Pass the index of the paired device
if (pairedDevices.size() > 0) {
callButtons(pairedDevices.iterator().next()); // First element in set.
} else {
System.out.println("No paired Device!");
}
}
});
acceptThread = new AcceptThread();
acceptThread.start();
}
}
private class ScanReciever extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
System.out.println("Started");
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
System.out.println("finished");
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("FOUND: " + device.getName());
deviceList.add(device);
arrayAdapter.add(device.getName()+" - Click to pair");
arrayAdapter.notifyDataSetChanged();
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
System.out.println("Connected~!!!!!!!!!!!!!!");
callButtons(deviceList.get(deviceList.size()-1));
}
}
};
protected void askAdapterOn() {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
protected void scanForDevices() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
reciever = new ScanReciever();
registerReceiver(reciever, filter);
bluetooth_adapter.startDiscovery();
}
protected void callButtons(BluetoothDevice bd) {
bluetooth_adapter.cancelDiscovery();
Intent toButton = new Intent(getApplicationContext(), buttons.class);
toButton.putExtra("selected",bd);
startActivity(toButton);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK){
if (bluetooth_adapter.isEnabled()){
onButton.setEnabled(false);
scanButton.setEnabled(true);
}
else {
onButton.setEnabled(true);
scanButton.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.menu_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDestroy() {
unregisterReceiver(reciever);
super.onDestroy();
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetooth_adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
System.out.println("READY TO ACCEPT");
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(socket);
try {
mmServerSocket.close();
} catch (IOException e) { }
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
}
Buttons.java(where the app will initiate a connection and maintain communication) - probably the file with the error:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
public class buttons extends Activity {
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
BluetoothDevice selected;
BluetoothAdapter bluetoothAdapter;
TextView tv;
Button button1;
Button button2;
Button button3;
Button unpairB;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
ConnectThread connectThread;
ConnectedThread connectedThread;
BluetoothSocket mmSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttons);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
selected = getIntent().getExtras().getParcelable("selected");
pair(selected);
connectedThread = null;
try {
connectedThread = new ConnectedThread(mmSocket);
connectedThread.start();
System.out.println("ConnectedThread started!");
} catch (Exception e) {
Log.e("unpair()", e.getMessage());
}
// Set up Buttons
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
unpairB = (Button) findViewById(R.id.unpairButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(2);
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(3);
}
});
unpairB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
unpair(selected);
finish();
}
});
// Set up textview
tv = (TextView) findViewById(R.id.textView);
tv.setText("connected to: " + selected.getName());
}
protected void buttonPressed(int i) {
connectedThread.write(i);
tv.setText(Integer.toString(i));
}
private void pair(BluetoothDevice device) {
connectThread = new ConnectThread(device);
connectThread.start();
}
private void unpair(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e("unpair()", e.getMessage());
}
}
private class ConnectThread extends Thread {
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
System.out.println("Socket was created in ConnectThread");
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
// bluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket) {
this.bluetoothSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
System.out.println("Connected to " + socket.getRemoteDevice().getName());
try {
tmpIn = bluetoothSocket.getInputStream();
tmpOut = bluetoothSocket.getOutputStream();
} catch (IOException e) {
}
inputStream = tmpIn;
outputStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
if (inputStream == null) System.out.println("Inputstream is null");
else System.out.println("Inputstream is safe");
if (outputStream == null) System.out.println("outstream is null");
else System.out.println("Outputstream is safe");
while (true) {
try {
System.out.println("Blocking?");
bytes = inputStream.read(buffer);
System.out.println("NO");
handler.obtainMessage(MESSAGE_READ, bytes, -1,
buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(int i) {
try {
byte[] buffer = new byte[1024];
buffer[0] = (byte) i;
outputStream.write(buffer);
outputStream.flush();
handler.obtainMessage(MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
System.out.println("Write SUCCESS!!!!!!!!!!!!!!");
} catch (IOException e) {
System.out.println("write ERRORRRRRRRRRRRRRRRRR");
}
}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
}
}
}
private final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WRITE:
System.out.println("Write was broadcasted");
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(Integer.toString(writeBuf[0]));
///tv.setText(writeMessage);
break;
case MESSAGE_READ:
System.out.println("Read was broadcasted");
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(Integer.toString(readBuf[0]));
tv.setText(readMessage);
break;
}
}
};
}

Android how to call a method of MainActivity in SmsReceiver Class

I'm very new to Android Programming, It would be really great if someone can help me in this.My project contains two JAVA files.
MainActivity.java extends Activity
SMSReceiver.java extends Broadcastreceiver
The SMSreceiver.java has the code which displays any incoming SMS in toast. Can you please tell me how to call a function in MainActivity whenever a particular SMS is received. For eg: when I receive sms called as starttemp it should call a function starttemp.
I have searched a lot and found that intents are a way to do this and we cannot call these methods directly. Please can anyone help me in this? And it would be really great if someone can send me working code.
This would be my MainACtivity.Java
package com.wissen.sms;
import android.annotation.SuppressLint;
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.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ToggleButton;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
#SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi" }) public class MainActivity extends Activity
{
TextView myLabel;
EditText myTextbox;
ToggleButton switch1;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
String status;
volatile boolean stopWorker;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button openButton = (Button)findViewById(R.id.open);
Button sendButton = (Button)findViewById(R.id.send);
Button closeButton = (Button)findViewById(R.id.close);
myLabel = (TextView)findViewById(R.id.label);
myTextbox = (EditText)findViewById(R.id.entry);
//switch1
switch1 = (ToggleButton) findViewById(R.id.switch1);
switch1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if(switch1.isChecked()){
try
{
String msg = "01ON";
msg += "\n\r";
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}
catch (IOException ex) { }
}else{
try
{
String msg = "01OF";
msg += "\n\r";
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}
catch (IOException ex) { }
}
}
});
//Open Button
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Send Button
sendButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
sendData();
}
catch (IOException ex) { }
}
});
//Close button
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
}
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
myLabel.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("HomeAutomation"))
{
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
status=data;
myLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
void sendData() throws IOException
{
String msg = myTextbox.getText().toString();
msg += "\n\r";
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}
void closeBT() throws IOException
{
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
}
This would be My SMSReceiver.Java
package com.wissen.sms.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
Toast toast = Toast.makeText(context, "Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast.show();
}
}
Now i want to call a method of MainActivity.java whenever a new message is received
void somemethod()
{
try
{
String msg = "01ON";
msg += "\n\r";
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}
catch (IOException ex) { }
}
}
One best way for use MainActivity method from Broadcast receiver class is
Define your method as a static and than you can use that method using below code
Activityname.methodname()
I tried this and its worked fine for me.
for example
public class SMSBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
if (intent.getAction() == SMS_RECEIVED) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
abc.methodtocall();
}
}
}
}
and your Activity code like this
public class abc extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public static void methodtocall(){
//Your code here...
}
}

Categories

Resources