I am using an Android 9 Pie API level. I am sending an available device using intent to another activity from below code using Broadcast in multiple ways.
Paired device list show perfectly but available nearby device not found when the search finishes. But don't know why it is not working.
private ActivityMainBinding binding;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<>();
private BluetoothAdapter mBluetoothAdapter;
private ProgressDialog mProgressDlg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setMessage("Scanning Device");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.cancelDiscovery();
}
});
if (mBluetoothAdapter == null) {
showUnsupported();
} else {
binding.btnViewPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
showToast("No Paired Devices Found");
} else {
ArrayList<BluetoothDevice> list = new ArrayList<>();
list.addAll(pairedDevices);
Intent intent = new Intent(MainActivity.this, DeviceListActivity.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
binding.btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.startDiscovery();
}
});
binding.btnEnable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}
}
});
if (mBluetoothAdapter.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
///////////////////////////////////////////////////////////////////////////////////////////
IntentFilter 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
public void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
binding.tvStatus.setText("Bluetooth is On");
binding.tvStatus.setTextColor(Color.GREEN);
binding.btnEnable.setText("Disable");
binding.btnEnable.setEnabled(true);
binding.btnViewPaired.setEnabled(true);
binding.btnScan.setEnabled(true);
}
private void showDisabled() {
binding.tvStatus.setText("Bluetooth is Off");
binding.tvStatus.setTextColor(Color.RED);
binding.btnEnable.setText("Enable");
binding.btnEnable.setEnabled(true);
binding.btnViewPaired.setEnabled(false);
binding.btnScan.setEnabled(false);
}
private void showUnsupported() {
binding.tvStatus.setText("Bluetooth is unsupported by this device");
binding.btnEnable.setText("Enable");
binding.btnEnable.setEnabled(false);
binding.btnViewPaired.setEnabled(false);
binding.btnScan.setEnabled(false);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
///// Boradcast recever to handle
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
showToast("Bluetooth Enabled");
showEnabled();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
showToast("Found device " + device.getName());
}
}
};
Related
I wanted to make bluetooth applications for arduino so that I could connect to the HC-05 module. And I found a tutorial on how to make a bluetooth connection (http://mcuhq.com/27/simple-android-bluetooth-application-with-arduino-example) When I downloaded the code from github, the application starts and everything works and connects. But the problem is that I can't open a new activity because the project is probably for 15 API and the new activity needs at least 16 so I decided to make such an application on my own based on the code from this website. And here I have a problem because when I make my phone search for bluetooth devices, nothing is displayed on my ListView.
This is my code `
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
offon = findViewById(R.id.BtBtn);
TV = findViewById(R.id.BtTv);
TV2 = findViewById(R.id.textView2);
TV3 = findViewById(R.id.bluetooth_status);
Next = findViewById(R.id.button2);
LV = findViewById(R.id.ListView);
disc = findViewById(R.id.button3);
ArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
adapter = BluetoothAdapter.getDefaultAdapter();
LV.setAdapter(ArrayAdapter);
LV.setOnItemClickListener(DeviceList);
handler = new Handler(Looper.getMainLooper()){
#Override
public void handleMessage(Message msg){
if(msg.what == MESSAGE_READ){
String readMessage = null;
readMessage = new String((byte[]) msg.obj, StandardCharsets.UTF_8);
TV2.setText(readMessage);
}
if(msg.what == CONNECTING_STATUS){
char[] sConnected;
if(msg.arg1 == 1)
TV3.setText(getString(R.string.BTConnected) + msg.obj);
else
TV3.setText(getString(R.string.BTconnFail));
}
}
};
if (adapter.isEnabled()){
TV.setText("Bluetooth ON");
}else TV.setText("Bluetooth OFF");
disc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
discovery();
if (!adapter.isEnabled()){
Toast.makeText(getBaseContext(), getString(R.string.BTnotOn), Toast.LENGTH_SHORT).show();
}
}
});
offon.setOnClickListener(new View.OnClickListener() {
#SuppressLint("MissingPermission")
#Override
public void onClick(View view) {
if (adapter.isEnabled()) {
adapter.disable();
TV.setText("Bluetooth OFF");
}else {
adapter.enable();
TV.setText("Bluetooth ON");
}
}
});
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
open2activity();
}
});
}
public void open2activity(){
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode, resultCode, Data);
}
#SuppressLint("MissingPermission")
private void discovery(){
if (adapter.isDiscovering()){
adapter.cancelDiscovery();
Toast.makeText(getApplicationContext(), getString(R.string.DisStop), Toast.LENGTH_SHORT).show();
}
else{
if (adapter.isEnabled()){
ArrayAdapter.clear();
adapter.startDiscovery();
Toast.makeText(getApplicationContext(), getString(R.string.DisStart), Toast.LENGTH_SHORT).show();
registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
}
final BroadcastReceiver blReceiver = new BroadcastReceiver() {
#SuppressLint("MissingPermission")
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ArrayAdapter.add(device.getName() + "\n" + device.getAddress());
ArrayAdapter.notifyDataSetChanged();
}
}
};
private AdapterView.OnItemClickListener DeviceList = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TV3.setText(getString(R.string.cConnet));
String info = ((TextView)view).getText().toString();
final String address = info.substring(info.length() - 17);
final String name = info.substring(0,info.length() - 17);
new Thread()
{
#SuppressLint("MissingPermission")
#Override
public void run() {
boolean fail = false;
BluetoothDevice device = adapter.getRemoteDevice(address);
try {
BTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), getString(R.string.ErrSockCrea), Toast.LENGTH_SHORT).show();
}
try {
BTSocket.connect();
} catch (IOException e) {
try {
fail = true;
BTSocket.close();
handler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
Toast.makeText(getBaseContext(), getString(ErrSockCrea), Toast.LENGTH_SHORT).show();
}
}
if(!fail) {
ConnectedThread = new ConnectedThread(BTSocket, handler);
ConnectedThread.start();
handler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
.sendToTarget();
}
}
}.start();
}
};
#SuppressLint("MissingPermission")
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
return (BluetoothSocket) m.invoke(device, BT_MODULE_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
return device.createRfcommSocketToServiceRecord(BT_MODULE_UUID);
}
}
`
I tried to do as above but nothing is displayed
I tried and followed some tutorial on web but it didn't work on new Android versions.
I declared all Bluetooth permissions and used Dexter permission library. I followed few answers but it doesn't display available Bluetooth device name also
Below is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toast("starts scanning...");
mBluetoothAdapter.startDiscovery();
}
});
mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String bluetoothDevice = mAdapter.getItem(i);
toast(bluetoothDevice);
}
});
}
public void pairedDevicesListView(View view){
mAdapter.clear();
pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices){
mAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
}
To discover a device, first get the bluetooth adapter by calling BluetoothAdapter.getDefaultAdapter()
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
To start discover, simply call the startDiscovery() from bluetooth adapter. This process is asynchronous so it will return immediately. To catch the discovery process, we can register a BroadcastReceiver with ACTION_FOUND, ACTION_DISCOVERY_STARTED, ACTION_DISCOVERY_STARTED. For each device found, the intent will carry extra field EXTRA_DEVICE containg the BluetoothDevice object.
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
adapter.startDiscovery();
The receiver:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
showToast("Found device " + device.getName());
}
}
};
And, don’t forget to unregister the receiver on Activity’s onDestroy method:
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
Add manifest permissions as follows
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />`
and try following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnstart=findViewById(R.id.btnstart);
mListView=findViewById(R.id.listofdevices);
final ArrayAdapter mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
mListView.setAdapter(mAdapter);
txt1=findViewById(R.id.txt1);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
setdevicevisible();
boolean hasBluetooth = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
if(!hasBluetooth) {
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
dialog.setTitle(getString(R.string.bluetooth_not_available_title));
dialog.setMessage(getString(R.string.bluetooth_not_available_message));
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();
MainActivity.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 another discovery is in progress, cancels it before starting the new one.
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
mAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
I forgot to declare Location permissions in the manifest file. To discover Bluetooth devices programmatically you need to add two permission i.e. ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION.
You could use the MAC address as unique ID.
And you can find in the official doc here a complete example of it
https://developer.android.com/guide/topics/connectivity/bluetooth.html#FindingDevices
About signal strength i think you should use RSSI (Received Signal Strength Indicator)
Edit: An easy way to accomplish this will be like this snippet to find bluetooth devices
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
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
hope it helps
happy coding
Try using this code, it worked for me.
public class DeviceListActivity extends Activity {
private ListView pairedDevicesListView, newDevicesListView;
private ArrayList<DeviceData> dataList= new ArrayList<DeviceData>();
private ArrayList<BluetoothDevice> pairedDevices=new ArrayList<BluetoothDevice>();
private BluetoothAdapter bluetoothAdapter;
BluetoothDevice device;
private ArrayAdapter newDeviceAdapter;
private DeviceListAdapter pairedDeviceAdapter;
public static String DEVICE_ADDRESS = "device_address";
private IntentFilter filter;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("action", action);
// Toast.makeText(DeviceListActivity.this, action, Toast.LENGTH_SHORT).show();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
newDeviceAdapter.add(device.getName() + "\n" + device.getAddress());
pairedDevices.add(device);
newDeviceAdapter.notifyDataSetChanged();
}
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
if (newDeviceAdapter.getCount() == 0) {
Toast.makeText(DeviceListActivity.this, "No devices found", Toast.LENGTH_SHORT).show();
newDeviceAdapter.add("No new device found");
newDeviceAdapter.notifyDataSetChanged();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_device_list);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevicesListView = (ListView) findViewById(R.id.avail_devices);
newDevicesListView=(ListView)findViewById(R.id.new_devices);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDeviceAdapter = new DeviceListAdapter(this,dataList, pairedDevices);
pairedDevicesListView.setAdapter(pairedDeviceAdapter);
pairedDeviceAdapter.notifyDataSetChanged();
//-----------------------------------------------
newDeviceAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
newDevicesListView.setAdapter(newDeviceAdapter);
newDeviceAdapter.notifyDataSetChanged();
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
// get paired devices
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
// pairedDeviceAdapter.clear();
for(BluetoothDevice device : pairedDevice)
{
// pairedDeviceAdapter.add(device.getName()+ "\n" +device.getAddress());
dataList.add(new DeviceData(device.getName(),device.getAddress()));
pairedDevices.add(device);
}
pairedDeviceAdapter.notifyDataSetChanged();
}
// register broadcast receiver
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);
pairedDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String data = ((TextView) view).getText().toString();
String address = data.substring(data.length() - 17);
Intent intent = new Intent();
intent.putExtra("device_address", address);
intent.putExtra("info", data);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
newDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
Boolean isBonded = false;
try {
isBonded = createBond(device);
if(isBonded)
{
Log.i("Log","Paired");
// pairedDeviceAdapter.add(device.getName() + "\n" + device.getAddress());
dataList.add(new DeviceData(device.getName(),device.getAddress()));
newDeviceAdapter.remove(device.getName() + "\n" + device.getAddress());
pairedDeviceAdapter.notifyDataSetChanged();
newDeviceAdapter.notifyDataSetChanged();
// Toast.makeText(DeviceListActivity.this, "paired to:" +device.getName(), Toast.LENGTH_SHORT).show();
// ------------------------
// Intent intent = new Intent();
// intent.putExtra("device_address", device.getAddress());
// intent.putExtra("info", device.getName());
// setResult(Activity.RESULT_OK, intent);
// finish();
}
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(broadcastReceiver, filter);
}
#Override
protected void onPostResume() {
super.onPostResume();
registerReceiver(broadcastReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (bluetoothAdapter != null) {
bluetoothAdapter.cancelDiscovery();
}
this.unregisterReceiver(broadcastReceiver);
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
}
I've looked at quite a lot of topics on this in different forums and none seem to help me.
I recently bought an Elegoo car kit, which is compatible with the Arduino IDE, and it comes with different types of code and what not. they even have their own Android app.
My problem is I want to create my own android Bluetooth application that connects/pairs with the module and can control the car remotely. I have my application up and running, it can scan for nearby devices and the HC-08 module appears in the list but I am not able to connect. when I try to connect it says it can't communicate with HC-08. I am pretty sure the problem lies in the android end as the elegoo Bluetooth app connects no problem at all with the Bluetooth module if there is any code on the elegoo board or not. The bluetooth module is a HC-08.
Can someone help me with this ?
Also I am following this youtube tutorial so the credit goes to him for the code.
https://www.youtube.com/watch?v=YJ0JQXcNNTA
Here is the main activity code:
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener{
private static final String TAG = "MainActivity";
BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
/**
* Broadcast Receiver for changes made to bluetooth states such as:
* 1) Discoverability mode on/off or expire.
*/
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG, "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG, "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
/**
* Broadcast Receiver for listing devices that are not yet paired
* -Executed by btnDiscover() method.
*/
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
/**
* Broadcast Receiver that detects bond state changes (Pairing status changes)
*/
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
}
}
}
};
#Override
protected void onDestroy() {
Log.d(TAG, "onDestroy: called.");
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
//mBluetoothAdapter.cancelDiscovery();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable(View view) {
Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover(View view) {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
}
}
}
/// Here is also my DeviceListAdapter code:
public class DeviceListAdapter extends ArrayAdapter<BluetoothDevice> {
private LayoutInflater mLayoutInflater;
private ArrayList<BluetoothDevice> mDevices;
private int mViewResourceId;
public DeviceListAdapter(Context context, int tvResourceId, ArrayList<BluetoothDevice> devices){
super(context, tvResourceId,devices);
this.mDevices = devices;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = tvResourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflater.inflate(mViewResourceId, null);
BluetoothDevice device = mDevices.get(position);
if (device != null) {
TextView deviceName = (TextView) convertView.findViewById(R.id.tvDeviceName);
TextView deviceAdress = (TextView) convertView.findViewById(R.id.tvDeviceAddress);
if (deviceName != null) {
deviceName.setText(device.getName());
}
if (deviceAdress != null) {
deviceAdress.setText(device.getAddress());
}
}
return convertView;
}
}
Some of the tutorials on Bluetooth are pretty old! I just got Arduino-Android Bluetooth communication working last week so this should work for you! First in your manifest file add these permissions:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then use this in your main.
public class MainActivity extends AppCompatActivity {
private final String DEVICE_ADDRESS="benamekhoda"; //I actually used Device Name instead of address
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Serial Port Service UUID
private BluetoothDevice device; //Our Bluetooth 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);
editText = (EditText) findViewById(R.id.edittext);
textView = (TextView) findViewById(R.id.textview);
startButton = (Button) findViewById(R.id.buttonStart);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(BTinit())
{
if(BTconnect())
{
setUiEnabled(true);
deviceConnected=true;
beginListenForData();
textView.append("\nConnection Opened!\n");
}
else{
Toast.makeText(getApplicationContext(),"BTconnect false",Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getApplicationContext(),"BTinit false",Toast.LENGTH_SHORT).show();
}
}
});
sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(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");
}
});
clearButton = (Button) findViewById(R.id.buttonClear);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onClickClear(view);
}
});
stopButton = (Button) findViewById(R.id.buttonStop);
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onClickSend(view);
}
});
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(); //Something like ArrayList but no duplicate is allowed and data is unordered
if(bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
}
else
{
for (BluetoothDevice iterator : bondedDevices)
{
if(iterator.getName().equals(DEVICE_ADDRESS))
{
device=iterator;
Toast.makeText(getApplicationContext(),"found the device",Toast.LENGTH_SHORT).show();
found=true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
boolean connected=true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw1",Toast.LENGTH_SHORT).show();
connected=false;
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw2",Toast.LENGTH_SHORT).show();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"throw3",Toast.LENGTH_SHORT).show();
}
}
return connected;
}
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;
Toast.makeText(getApplicationContext(),"throw4",Toast.LENGTH_SHORT).show();
}
}
}
});
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("");
}
}
I got it from this awesome tutorial by Hariharan Mathavan from All About Circuits.
Can any one tell me the callback method the bellow code. Is there any other efficient code available for this purpose???
private void pairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Toast.makeText(getBaseContext(),"Exception: "+e.getMessage(),Toast.LENGTH_LONG ).show();
}
}
For better clarification I added the full code. I want to do something on the pairing completion
public class BtScan extends AppCompatActivity {
Button bt;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
IntentFilter filter;
BroadcastReceiver receiver;
ArrayAdapter<String> listAdapter;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_bluetooth_scan);
BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = bluetoothManager.getAdapter();
if (!btAdapter.isEnabled()) {
turnOnBT();
}
SharedPreferences prefs = getSharedPreferences("Selected bt", MODE_PRIVATE);
String tmp=prefs.getString("mac","");
if(!tmp.equals("")){
Intent intent=new Intent(getBaseContext(),BtIns.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("MAC",tmp);
startActivity(intent);
}
else {
bt = (Button) findViewById(R.id.my_bT_scan);
bt.setTransformationMethod(null);
listView = (ListView) findViewById(R.id.my_listViewscan);
newScan();
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newScan();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery();
}
SharedPreferences.Editor editor = getSharedPreferences("Selected bt", MODE_PRIVATE).edit();
editor.putString("mac", devices.get(i).getAddress());
editor.commit();
if (!listAdapter.getItem(i).contains("Paired")) {
try {
BluetoothDevice selectedDevice = devices.get(i);
pairDevice(selectedDevice);
Thread.sleep(500);
newScan();
} catch (Exception e) {
}
} else {
BluetoothDevice selectedDevice = devices.get(i);
Intent intent = new Intent(getBaseContext(), BtIns.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("MAC", selectedDevice.getAddress());
startActivity(intent);
}
}
});
}
}
private void newScan(){
btAdapter.cancelDiscovery();
Toast.makeText(getBaseContext(),"New Scan Start",Toast.LENGTH_SHORT ).show();
listAdapter= new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
devices = new ArrayList<BluetoothDevice>();
btAdapter.startDiscovery();
}
private void getPairedDevices() {
devicesArray = btAdapter.getBondedDevices();
if(devicesArray.size()>0){
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName());
}
}
}
void turnOnBT(){
Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intent);
}
void init(){
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Toast.makeText(getBaseContext(),"new br: "+action,Toast.LENGTH_LONG ).show();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
pairedDevices=new ArrayList<String>();
getPairedDevices();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//Toast.makeText(getBaseContext(),"Dev: "+device.getName(),Toast.LENGTH_LONG ).show();
devices.add(device);
String s = "";
for(int a = 0; a < pairedDevices.size(); a++){
if(device.getName().equals(pairedDevices.get(a))){
//append
s = "(Paired)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}
else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if(btAdapter.getState() == btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
}
private void pairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Toast.makeText(getBaseContext(),"Exception: "+e.getMessage(),Toast.LENGTH_LONG ).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
btAdapter.cancelDiscovery();
unregisterReceiver(receiver);
}
catch (Exception e){}
}
#Override
protected void onPause() {
super.onPause();
try {
btAdapter.cancelDiscovery();
unregisterReceiver(receiver);
}
catch (Exception e){}
}
#Override
public void onResume() {
super.onResume();
try {
init();
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
//Toast.makeText(getBaseContext(),"Registration",Toast.LENGTH_SHORT ).show();
}
catch (Exception e){}
}
}
I want to find if bluetooth scanner is connected to my android mobile or not after every 7 seconds. For that I created a receiver where I found the bondeddevices and then its majorclass. But its not working not finding any device. What might be the problem?
Here's the Activity class:
public class Activity_Home extends ActionBarActivity implements
OnClickListener {
CountDownTimer wifiTimer, timer;
BluetoothAdapter mBluetoothAdapter;
BluetoothDevice bluetoothDevice;
CheckBluetoothScanner mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReceiver = new CheckBluetoothScanner();
isScannerConnected();
}
private void isScannerConnected() {
timer = new CountDownTimer(Long.MAX_VALUE, 7000) { // -------call
// amethod
// after
// certain
// time
// interval-------
// This is called every interval. (Every 7 seconds in this example)
public void onTick(long millisUntilFinished) {
Log.d("test", "Timer tick");
System.out.println("=======bluetooth--start");
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
IntentFilter filter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
System.out.println("============utility: "
+ Utility.SCANNER_ON);
if (Utility.SCANNER_ON.equalsIgnoreCase("true")) {
tv_scanner
.setBackgroundResource(R.drawable.scanner);
} else {
tv_scanner.setBackgroundResource(0);
}
} else {
tv_scanner.setBackgroundResource(0);
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void onFinish() {
Log.d("test", "Timer last tick");
timer.cancel();
}
}.start();
}
Here's the receiver class:
public class CheckBluetoothScanner extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
}
else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Set pairedDevices = BluetoothAdapter.getDefaultAdapter()
.getBondedDevices();
BluetoothDevice device1 = null;
for (Object item : pairedDevices) {
device1 = (BluetoothDevice) item;
}
BluetoothClass bluetoothClass = device1.getBluetoothClass();
System.out.println("======bluetoothClass"+bluetoothClass);
if (bluetoothClass != null) {
int deviceClass = bluetoothClass.getDeviceClass();
System.out.println("=======deviceclass:"+deviceClass);
if (deviceClass == Device.Major.IMAGING
|| deviceClass == Device.Major.PERIPHERAL) {
Utility.SCANNER_ON = "true";
} else {
Utility.SCANNER_ON = "false";
}
}
}
}
};