Send bluetooth message via Android Studio - java

I'm trying to send a message via bluetooth in Android Studio. I've googled but I cannot find the answer. I want to send a message to a connected device.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ImageView bluetoothOnImageView;
private ImageView bluetoothOffImageView;
private TextView bluetoothOnOffTextView;
private BluetoothAdapter bluetoothAdapter;
private ListView listView;
private EditText messageEditText;
private ArrayList<String> deviceList = new ArrayList<String>();
private ArrayList<BluetoothDevice> deviceListBluetooth = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothOnImageView = findViewById(R.id.bluetoothOnImageView);
bluetoothOffImageView = findViewById(R.id.bluetoothOffImageView);
bluetoothOnOffTextView = findViewById(R.id.bluetoothOnOffTextView);
listView = findViewById(R.id.listView);
messageEditText = findViewById(R.id.messageEditText);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
checkBluetooth();
Toast.makeText(this, "Scanning devices...", Toast.LENGTH_SHORT).show();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
IntentFilter filterChange = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(receiverChange, filter);
listView.setOnItemClickListener(MainActivity.this);
}
private final BroadcastReceiver receiverChange = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 3 Cases
// 1: Bonded already
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.d("BroadcastReceiver", "BOND_BONDED");
Toast.makeText(MainActivity.this, "Already connected to this device.", Toast.LENGTH_SHORT).show();
}
// 2: Creating a bond
if (device.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d("BroadcastReceiver", "BOND_BONDING");
}
// 3: Breaking a bond
if (device.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d("BroadcastReceiver", "BOND_NONE");
Toast.makeText(MainActivity.this, "Broke connection to this device.", Toast.LENGTH_SHORT).show();
}
}
}
};
public void bluetoothSearchOnClick(View view) {
Toast.makeText(this, "Rescanning devices...", Toast.LENGTH_SHORT).show();
// Reset devices
deviceList.clear();
deviceListBluetooth.clear();
bluetoothAdapter.startDiscovery();
checkBluetooth();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
}
#Override
protected void onDestroy() {
unregisterReceiver(receiver);
unregisterReceiver(receiverChange);
super.onDestroy();
}
private final BroadcastReceiver receiver = 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);
String newDevice = device.getName() + "\n" + device.getAddress();
boolean duplicate = false;
// No duplicate devices
for (int i = 0; i < deviceList.size(); i++) {
if (newDevice.equals(deviceList.get(i))) {
duplicate = true;
}
}
if (!duplicate) {
deviceList.add(newDevice);
deviceListBluetooth.add(device);
}
Log.i("BT", device.getName() + "\n" + device.getAddress());
listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, deviceList));
}
}
};
public void bluetoothOnOnClick(View view) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.disable();
// Wait x milliseconds
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
checkBluetooth();
}
}, 500);
}
public void bluetoothOffOnClick(View view) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.enable();
// Wait x milliseconds
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
checkBluetooth();
}
}, 500);
}
private void checkBluetooth() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(this, "This device does not support Bluetooth", Toast.LENGTH_SHORT).show();
} else if (!bluetoothAdapter.isEnabled()) {
// Bluetooth is not enabled :)
bluetoothOnImageView.setVisibility(View.GONE);
bluetoothOffImageView.setVisibility(View.VISIBLE);
bluetoothOnOffTextView.setText("OFF");
bluetoothOnOffTextView.setTextColor(Color.RED);
} else {
// Bluetooth is enabled
bluetoothOffImageView.setVisibility(View.GONE);
bluetoothOnImageView.setVisibility(View.VISIBLE);
bluetoothOnOffTextView.setText("ON");
bluetoothOnOffTextView.setTextColor(Color.GREEN);
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
checkBluetooth();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
Log.d("Bluetooth Adapter", "onItemClick: You Clicked on a device.");
String[] device = deviceList.get(position).split("\n");
String deviceName = device[0];
// Bond
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
Log.d("Bluetooth Adapter", "Trying to pair with " + deviceName);
deviceListBluetooth.get(position).createBond();
}
}
public void sendButtonOnClick(View view) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Send message
}
}
In the method sendButtonOnClick(View view) is where I want to send the message. You can find this method at the bottom of the code.
Can anyone help me?

this is not so simple as you think (packing up messaging feature into one method). you need to connect to BluetoothSocket obtained from BluetoothDevice using createRfcommSocketToServiceRecord and knowing "messaging" UUID (you can list them with getUuids() method). after proper socket connection you can obtain input and output streams (getInputStream and getOutputStream), from which you can read and write bytes converting to text if you want. found pretty good sample in HERE, which is using separated Threads for Bluetooth communication making whole feature async and not hanging main/UI thread

Related

Pairing new device in Lock Task Mode (Android P/10)

I have an issue when I use the Lock Task Mode (Kiosk mode) on Android.
In "normal" mode, when I try to pair a device, a pop-up message appears :
"Are you sure you want to pair the Bluetooth Device?" Yes/No
But in Lock Task Mode, the message doesn't appear.
I added in my code to authorize notifications but pop-up are not displayed :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
int test = dmp.getLockTaskFeatures(adminComponentName);
dmp.setLockTaskFeatures(adminComponentName, DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO |
DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS |
DevicePolicyManager.LOCK_TASK_FEATURE_HOME);
}
Is there a way in Lock Task Mode to authorize such pop-ups?
Thanks
public class Bluetooth extends AppCompatActivity {
ArrayList<String> listItems=new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
BroadcastReceiver mReceiver;
DevicePolicyManager dpm;
ComponentName deviceAdmin;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
dpm = (DevicePolicyManager) Bluetooth.this.getSystemService(Context.DEVICE_POLICY_SERVICE);
deviceAdmin = new ComponentName(Bluetooth.this, MyDeviceAdminReceiver.class);
dpm.setLockTaskPackages(deviceAdmin, new String[]{
Bluetooth.this.getPackageName()
"com.android.settings"
});
ListView lista=findViewById(R.id.devices);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
lista.setAdapter(adapter);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//setdevicevisible();
boolean hasBluetooth = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
if(!hasBluetooth) {
AlertDialog dialog = new AlertDialog.Builder(Bluetooth.this).create();
dialog.setTitle("Bluetooth nem elérhető");
dialog.setMessage("Bluetooth ki van kapcsolva!");
dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Closes the dialog and terminates the activity.
dialog.dismiss();
Bluetooth.this.finish();
}
});
dialog.setCancelable(false);
dialog.show();
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
//device.setPairingConfirmation(true);
if (device.getName() != null) {
adapter.add(device.getName() + "\n" + device.getAddress());
device.createBond();
}
//adapter.add(device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
try{
unregisterReceiver(mReceiver);
dpm.setLockTaskPackages(deviceAdmin, new String[]{
Bluetooth.this.getPackageName()
});
}catch (Exception e){
// already unregistered
}
}
}

scaning bluetooth (java) on android studio

I am developing the attendance system using Bluetooth that allow the user to scan Bluetooth to get the Bluetooth address and compare it with registered Bluetooth address. The problem is, it only scan and display the registered list of student but not listing the available Bluetooth and also not compare with the register Bluetooth address.
here is the code for BluetoothScanActivity
public class BluetoothScanActivity extends AppCompatActivity {
public static final String TAG = BluetoothScanActivity.class.getSimpleName();
BluetoothAdapter mBluetoothAdapter;
IntentFilter filter;
BroadcastReceiver mReceiver;
String name[];
ArrayList<String> macID;
Bundle scan_data;
int countScans=0;
int numCountScans;
int value;
RippleBackground rippleBackground;
String classID;
boolean selectDateCheck = false;
Date selectedDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_scan);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(ContextCompat.getColor(getBaseContext(), R.color.main_blue));
}
classID = getIntent().getStringExtra("Class ID");
numCountScans = getIntent().getIntExtra("Number Scans",3);
value = getIntent().getIntExtra("Value",1);
selectDateCheck = getIntent().getBooleanExtra("Manual Date",false);
selectedDate = (Date)getIntent().getSerializableExtra("Selected Date");
Toast.makeText(this, numCountScans + " " + value, Toast.LENGTH_LONG).show();
rippleBackground = (RippleBackground)findViewById(R.id.content);
int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
init();
if(mBluetoothAdapter==null)
{
Toast.makeText(getApplicationContext(),"Your device doesn't support bluetooth!",Toast.LENGTH_SHORT).show();
finish();
}
else
{
if (!mBluetoothAdapter.isEnabled()) {
turnOnBT();
}
}
scan_data=new Bundle();
name=new String[100];
macID = new ArrayList<String>();
Log.d(TAG, "onCreate: ");
searchDevices();
}
private void turnOnBT() {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
public void init()
{
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//Create a BroadCastReceiver for ACTION_FOUND
mReceiver=new BroadcastReceiver()
{
#Override
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 address to an array adapter to show in a ListView
if(!macID.contains(device.getAddress().toUpperCase()))
macID.add(device.getAddress().toUpperCase());
Toast.makeText(context,device.getName(),Toast.LENGTH_SHORT).show();
}
else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals((action)))
{
if(mBluetoothAdapter.getState()== BluetoothAdapter.STATE_OFF) {
turnOnBT();
}
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals((action)))
{
if(countScans == numCountScans-1)
{
rippleBackground.stopRippleAnimation();
Intent in = new Intent(BluetoothScanActivity.this, MarkStudentsActivity.class);
in.putExtra("Class ID", classID);
in.putExtra("Value",value);
in.putStringArrayListExtra("MAC ID's", macID);
intent.putExtra("Manual Date",selectDateCheck);
intent.putExtra("Selected Date",selectedDate);
startActivity(in);
finish();
}
else
{
countScans++;
Log.d("Mark","" + countScans);
mBluetoothAdapter.startDiscovery();
}
}
}
};
filter=new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
if(mBluetoothAdapter!=null)
mBluetoothAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}

Bluetooth LeScan didn't on target

My android studio has bluetooth permission in manifest,
and here is my code:
private BluetoothManager bluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private static final long SCAN_PERIOD = 1000000; //10 seconds 搜尋頻率 1S:1000
private Handler mHandler;
private NotificationManager notificationManager;
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//推播接收媒介
mHandler = new Handler();
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
//檢查是否支援藍芽
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "硬體不支援", Toast.LENGTH_SHORT).show();
}
// 檢查手機是否開啟藍芽裝置
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Toast.makeText(this, "請開啟藍芽裝置", Toast.LENGTH_SHORT).show();
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT);
} else {
scanLeDevice(true);
}
};
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
//判斷是否有重新申請推播的必要
//BEACON 取其名稱
notificationManager.cancelAll();//清理舊的通知資料
prb=device.getName().toString();
noti.addJavascriptInterface(new JsOperation(),"test1");
}
};
};
I has test the mBluetoothAdapter.startLeScan(mLeScanCallback);,
the result is true, but can't step into onLeScan ,
I'm pretty sure the BLE device has sign.
please help me.
In addition to android.permission.BLUETOOTH you also need android.permission.ACCESS_COARSE_LOCATION in the manifest. Make sure you use the permission API to prompt the user for BLUETOOTH permission.
Your code won't enter mLeScanCallback.onLeScan() until a device is discovered. Use nRF Connect to verify there are discoverable Bluetooth LE devices around you.

How do I access deviceName and deviceHardwareAddress from within this object?

I have the following lines of code. I'm trying to access the Strings deviceName and deviceHarwareAddress. Do I need to construct a class that extends BroadcastReceiver and create a method within that which will return the code for me?
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
}
}
};
Not necessary. If you are limiting its use within a single component (say activity/fragment/service), you can keep "mReceiver" inside that component and then register mReceiver for that. That will work fine.
This is the case if you are doing it inside an activity.
public class BluetoothTest extends AppCompatActivity {
private ArrayList<BluetoothDevice> deviceList;
private BluetoothAdapter mBluetoothAdapter;
private ArrayList<DeviceItem> deviceItemList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
/**
* Do necessary coding to enable bluetooth
*/
registerReceiver();
startBluetoothDiscovery();
}
private void registerReceiver() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter dintentFilter = new IntentFilter();
dintentFilter.addAction(BluetoothDevice.ACTION_FOUND);
dintentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
dintentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mDiscoveryBroadcastReceiver, dintentFilter);
}
public void startBluetoothDiscovery() {
if (!mBluetoothAdapter.isDiscovering())
mBluetoothAdapter.startDiscovery();
}
public void setBluetoothDevice(BluetoothDevice device) {
if (!deviceList.contains(device))
deviceList.add(device);
}
public ArrayList<BluetoothDevice> getBluetoothDeviceList() {
return deviceList;
}
private void resetAll() {
deviceItemList.clear();
unregisterReceiver(mDiscoveryBroadcastReceiver);
}
private final BroadcastReceiver mDiscoveryBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(getApplicationContext(), "Started discovery!!!", Toast.LENGTH_SHORT).show();
deviceList = new ArrayList<>();
deviceItemList.clear();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(getApplicationContext(), "Finished discovery!!!", Toast.LENGTH_SHORT).show();
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
DeviceItem deviceItem = new DeviceItem(device.getName(),
device.getAddress(), device.getBluetoothClass(), device);
deviceItem.setBluetoothDevice(device);
/**
* To check if the device is in paired list or not
*/
if (mBluetoothAdapter.getBondedDevices().contains(device))
deviceItem.setPaired(true);
else
deviceItem.setPaired(false);
if (!deviceItemList.contains(deviceItem))
deviceItemList.add(deviceItem);
/**
* Once the device is found,it is added to a list
*/
setBluetoothDevice(device);
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings;
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
}
In case of "service" you can make use of the binder or observer pattern for make the data available to the activity.

How to read/receive data using bluetooth?

I'm trying to make an app that can send and receive data via bluetooth from arduino. The part where i send the data is fairly simple so I've managed to get it right. I got stuck at receiving data.
My program has 2 layouts. First there is a layout with a CONNECT button and some buttons that change the layout. This is the code:
Public class MainActivity extends AppCompatActivity {
ImageButton test, manual,connect;
Button back;
private BluetoothAdapter mbluetoothAdapter;
protected AlertDialog.Builder builder;
ConnectThread mBluetooth = new ConnectThread();
String mBluetoothName = "";
String mBluetoothAdress = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Context context = this;
//final LayoutInflater factory = getLayoutInflater();
//final View textEntryView = factory.inflate(R.layout.activity_main);
builder = new AlertDialog.Builder(this);
mbluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
connect = (ImageButton) findViewById(R.id.connect);
test = (ImageButton) findViewById(R.id.test);
manual = (ImageButton) findViewById(R.id.manual);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,SecondActivity.class );
context.startActivity(intent);
}
});
manual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,SecondActivity.class );
context.startActivity(intent);
}
});
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mbluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBtIntent);
} else {
if (!mBluetooth.mBluetoothAddress.equals("")) {//if another connection is already exits then close it first
stopAllActivities();
} else {
try {
Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class);
startActivityForResult(serverIntent, Helper.REQUEST_CONNECT_DEVICE);
} catch (Exception e) {
showToast(getString(R.string.errorOccured) + ": " + e.getMessage());
e.printStackTrace();
}
}
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Helper.REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
mBluetoothName = data.getExtras().getString(Helper.EXTRA_BLUETOOTH_NAME);
mBluetoothAdress = data.getExtras().getString(Helper.EXTRA_BLUETOOTH_ADDRESS);
// setBluetoothInfo();
showToast(R.string.connectedDevice + mBluetoothName);
if (!mBluetoothAdress.equals("")) {
if (!mBluetooth.connect(mBluetoothAdress)){
}
}
}
break;
}
}
The SecondActivity contains the main purpose of this app: To send and receive data. This is how it looks like:
public class SecondActivity extends AppCompatActivity {
final Context context = this;
Button back;
ImageButton btnup, btndown, btnright, btnleft;
ConnectThread mBluetooth = new ConnectThread();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnup = (ImageButton) findViewById(R.id.btnup);
btndown = (ImageButton) findViewById(R.id.btndown);
btnleft = (ImageButton) findViewById(R.id.btnleft);
btnright = (ImageButton) findViewById(R.id.btnright);
final TextView direction = (TextView) findViewById(R.id.text_direction);
final TextView steering = (TextView) findViewById(R.id.steering_direction);
final TextView speed = (TextView) findViewById(R.id.speed);
final TextView battery = (TextView) findViewById(R.id.batery);
final Chronometer chronometer = (Chronometer) findViewById(R.id.chronometer);
btndown.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mBluetooth.write("2");
direction.setText(R.string.Backwards);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
mBluetooth.write("x");
direction.setText(R.string.blank);
}
return false;
}
});
Note: I didnt post the whole code because i have more buttons with the exact same code as the one above.
For the Bluetooth connection i have 2 separate classes one called ConnectThread:
public class ConnectThread {
BluetoothAdapter mBluetoothAdapter = null;
BluetoothSocket mSocket = null;
OutputStream mOutStream = null;
InputStream mInStream=null;
String mBluetoothAddress = "";
public boolean connect(String bluetoothAddress) {
if (!mBluetoothAddress.equals(bluetoothAddress) && !mBluetoothAddress.equals("")) {
close();
}
mBluetoothAddress = bluetoothAddress;
if (mBluetoothAdapter == null) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
if (mBluetoothAdapter == null) {
return false;
}
if (!mBluetoothAdapter.isEnabled()) {
return false;
}
try {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mBluetoothAddress);
if (mSocket == null) {
mSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
mSocket.connect();
}
} catch (IOException e) {
mSocket = null;
e.printStackTrace();
return false;
}
try {
mOutStream = mSocket.getOutputStream();
} catch (IOException e) {
mOutStream = null;
e.printStackTrace();
return false;
}
return true;
}
public boolean check() {
if (mBluetoothAdapter == null) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
if (mBluetoothAdapter == null) {
return false;
}
if (!mBluetoothAdapter.isEnabled()) {
return false;
}
if (!mSocket.isConnected()) {
return false;
}
return true;
}
public boolean close() {
try {
if (mOutStream != null) {
mOutStream.close();
}
if (mSocket != null) {
mSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
mOutStream = null;
mSocket = null;
return true;
}
public boolean write(String strData) {
byte[] buffer = strData.getBytes();
try {
if (mOutStream != null && mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
mOutStream.write(buffer);
}
else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
And the other one DeviceListActivity:
public class DeviceListActivity extends Activity {
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
// Set result CANCELED incase the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mBtAdapter == null)
return;
doDiscovery();
v.setVisibility(View.GONE);
}
});
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBtAdapter == null) {
mPairedDevicesArrayAdapter.add("DUMMY\n00:00:00:00:00:00");
return;
}
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null)
mBtAdapter.cancelDiscovery();
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
if (mBtAdapter == null)
return;
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
// The on-click listener for all devices in the ListViews
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
if (mBtAdapter != null) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
}
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String name = info.substring(0, info.length() - 18);
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(Helper.EXTRA_BLUETOOTH_ADDRESS, address);
intent.putExtra(Helper.EXTRA_BLUETOOTH_NAME, name);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
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);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
for (int i = 0; i < mNewDevicesArrayAdapter.getCount(); i++) {
if (mNewDevicesArrayAdapter.getItem(i).equals(device.getName() + "\n" + device.getAddress())) {
return;
}
}
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
I want to update two TextView with the data i receive from arduino. The data would look something like #first_data,second_data* where # is the start of data series and * the end. I would appreciate if you can help me with some advice/code how to do that. I am pretty new to java and I still dont fully understand how everything works.
Once you get the Bluetooth socket you could use its stream to read/write the content.
...
m_Input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
m_Output = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
...
// reading from stream
m_Input.read(buffer, readBytes, 1) ;
you could use
m_Input.available()
to check if is any data available into stream. Otherwise the read method will block until you will read the number of bytes you specified as third argument.
int readBytes=0;
while(readBytes < expectedBytes){
timeout = 0;
while((m_Input.available()) == 0 && timeout < ReadTimeout) {
timeout+=250;
// throws interrupted exception
Thread.sleep(250);// let control to other threads
}
if(timeout >= ReadTimeout){
// throw new timeout exception
}
if (m_Input.read(buffer, readBytes, 1) == -1) {
// throw stream/socket closed
}
readBytes++;
}
Ad for writing use write method
...
//writting to stream
m_Output.write(buffer,..);

Categories