in Android, how do we periodically scan for bluetooth devices? - android

The bluetooth scan should stop as soon as it finds a device of choice, and then after stopping it should start again, when i do the following, i get error saying the app has stopped. i want to scan for 3 times, and store their radiuses.
private BluetoothAdapter mBtAdapter;
mBtAdapter.startDiscovery();
//this string stores the MAC Address of the required device
string name = "12:34:D3:s3:we";
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))
{
if(device.getAddress.equals(name)){
mBtAdapter.cancelDiscovery();
}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
mBtAdapter.startDiscovery();
}
}
}

Related

Android Bluetooth - Getting NULL for UUID of bluetooth discovered devices

I want to share the data between 2 bluetooth devices without pairing and in both the phones my app will be installed
so i used this method (https://arxiv.org/ftp/arxiv/papers/1507/1507.00650.pdf)
Bluetooth device advertises a list of services using UUIDs numbers.
This how registered a service=====>
String uuid = "f2989d52-b3d6-4205-b34d-04f35ea264e5";
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothServerSocket btSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("MYAPP", UUID.fromString(uuid))
Intents for callback===>
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter1);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_UUID);
registerReceiver(mReceiver, filter2);
After that i call
bluetoothAdapter.startDiscovery(); // to start discovery of devices
Code to handle intents==>
private final BroadcastReceiver mReceiver = new
BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.e("SUNIL","receiver");
String action = intent.getAction();
Log.e("SUNIL","receiver action"+action);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Boolean uuid1 = device.fetchUuidsWithSdp();
mDeviceList.add(device);
Log.e("SUNIL","device uuid result"+uuid1);
Log.e("SUNIL","device"+device.getAddress()+device.getUuids()+device.getBondState());
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// discovery has finished, give a call to fetchUuidsWithSdp on first device in list.
if (!mDeviceList.isEmpty()) {
BluetoothDevice device = mDeviceList.remove(0);
boolean result = device.fetchUuidsWithSdp();
Log.e("SUNIL", "device uuid result223" + result+"==uuid finished"+device.getUuids());
}
}
else if (BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e("SUNIL","device.getUuids()"+device.getUuids());
Parcelable[] uuids = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
if(uuids != null) {
for (Parcelable ep : uuids) {
if (uuids != null) {
String uuid = ep.toString();
Log.e("SUNIL", "uuid===>" + uuid+"===="+device.getName());
**getting uuid null here**
}
}
}
}
}
};
Please help me and i am new to this bluetooth API's
I have trued with redmi 6A and redmi 6 PRO devices

BluetoothSocket.isConnected issue

I have created an Android Application in that if my Android has a Bluetooth connection to my computer and I power down my computer, isConnected still returns true. Anyone know if this can be fixed?
I'm not sure if there's a Bluetooth heartbeat or not.
Try this.
IntentFilter connectivityFilter = new IntentFilter();
connectivityFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
connectivityFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
registerReceiver(bluetoothModeCheckingReceiver, connectivityFilter);
private final BroadcastReceiver bluetoothModeCheckingReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
// to do
} else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
// to do
}
}
};

Android speech recognition over Bluetooth headset sometimes omits beep to prompt user to speak

My app already does speech recognition. A user told me it didn't work with a Bluetooth headset. I was able to, mostly, get speech recognition working over the Bluetooth headset (thanks to another Stack Overflow contributor, no thanks to the official Android documentation).
There is one annoying problem, however: when switching to use the Bluetooth headset, it can obliterate audio output briefly during the switchover. In particular, it can sometimes omit the beep that ordinarily prompts the user for speech recognition.
My current workaround is to put in a one-second delay, after the Bluetooth headset has been connected to the SCO audio channel, before doing speech recognition.
My question: is there a more reliable method of avoiding this conflict?
static AudioManager sAudioManager;
static BluetoothHeadset sBluetoothHeadset;
static BluetoothDevice sBluetoothDevice;
static public void initBluetooth(Context pContext)
{
sAudioManager = (AudioManager) pContext.getSystemService(Context.AUDIO_SERVICE);
// Register to get notifications about Bluetooth profiles
sBluetoothAdapter.getProfileProxy(
pContext, new BluetoothProfileListener(), BluetoothProfile.HEADSET);
// Register to receive notification when the headset is dis/connected
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
pContext.registerReceiver(
new BluetoothHeadsetBroadcastReceiver(), intentFilter);
}
public static void startSpeechRecognition()
{
sAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
sAudioManager.startBluetoothSco();
sAudioManager.setBluetoothScoOn(true);
sBluetoothHeadset.startVoiceRecognition(sBluetoothDevice);
}
public static void stopSpeechRecognition()
{
sBluetoothHeadset.stopVoiceRecognition(sBluetoothDevice);
sAudioManager.stopBluetoothSco();
sAudioManager.setBluetoothScoOn(false);
sAudioManager.setMode(AudioManager.MODE_NORMAL);
}
static public void doSpeechRecognition(Context pContext)
{
SpeechRecognizer sr = SpeechRecognizer.createSpeechRecognizer(pContext);
Intent intent =
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
sr.startListening(intent);
}
static public class BluetoothHeadsetBroadcastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context pContext, Intent pIntent)
{
int state = pIntent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
if (state == AudioManager.SCO_AUDIO_STATE_CONNECTED)
{
// CURRENT WORKAROUND
// Delay speech recognition to avoid obliterating beep prompt
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
};
doSpeechRecognition(pContext);
}
}
}
static public class BluetoothProfileListener implements BluetoothProfile.ServiceListener
{
#Override
public void onServiceConnected(int pProfile, BluetoothProfile pProxy)
{
sBluetoothHeadset = (BluetoothHeadset) pProxy;
List<BluetoothDevice> devices = pProxy.getConnectedDevices();
int numDevices = devices.size();
if (numDevices > 0)
{
BluetoothDevice device = devices.get(0);
sBluetoothDevice = device;
}
}
}

Discovering Bluetooth devices on Android

I've searched and tried everything I could, but I just can't get this to work. From all the examples I've seen, I seem to be doing the right thing, but maybe I'm missing something.
I'm trying to discover Bluetooth devices on Android and have been following the guide on the Android Developer page: http://developer.android.com/guide/topics/connectivity/bluetooth.html
I can enable BT when the app starts and get the name and address of my device. However, I can't see the names of other nearby devices (supposed to show up as a toast). The intriguing part is, when I enable BT before starting the app, it actually does what I want and shows the nearby devices' name.
Here's the code:
public class MainActivity extends AppCompatActivity {
TextView mTextView;
BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
final String status;
// Check BT support
if (mBluetoothAdapter == null){
// Device does not support BT
status = "Your device does not support Bluetooth";
}
else {
String myAddress = mBluetoothAdapter.getAddress();
String myName = mBluetoothAdapter.getName();
status = myName + ": " + myAddress;
}
mTextView = (TextView)findViewById(R.id.textView);
// If BT is enabled before app start, discover devices
// This is where things work, for some reason
if (mBluetoothAdapter.isEnabled()){
mTextView.setText(status);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver, filter);
getBTdevices();
}
// If BT is not enabled, enable it and look for devices
else{
mTextView.setText(status);
mBluetoothAdapter.enable();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver, filter);
getBTdevices();
}
}
protected void getBTdevices(){
// Stop discovery and start
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView textView = (TextView)findViewById(R.id.textView2);
textView.setText("Start");
String action = intent.getAction();
// If device is found
if (BluetoothDevice.ACTION_FOUND.equals(action)){
// Get BT device from intent
textView.setText("Device found");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(context, "Device found: "+ device.getName(), Toast.LENGTH_LONG).show();
System.out.println("Discovered!");
}
}
};
protected void onDestroy(){
super.onDestroy();
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(mBroadcastReceiver);
}
}
Some help would really be appreciated, I don't know what else I can do.
EDIT: Forgot to mention, I have set both the BLUETOOTH and BLUETOOTH_ADMIN permissions in the manifest.

Detect when USB device detached from Android device

I am using a usb POS printer with my application. I have successfully written the code to connect, request permission and print data. However, I'm unsure how do notify the user when the printer is disconnected, if it is then the device falls back to the network printer.
So this is my BroadcastReceiver for requesting permission:
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
mDevice = device;
if(mConnection == null){
Log.i(m_Tag, "Connection is null");
}
Log.i(m_Tag, "Connected successfully");
}else{
Log.i(m_Tag, "Device is null");
}
}
else {
}
}
}
}
};
I have trawled through the forums here and suggested answers and I've checked out this http://developer.android.com/guide/topics/connectivity/usb/host.html I can't find a solid way to do it without including a device filter xml file. I can't do this because I'm unsure as to what model of printer will be used by the end user.
My brain is fried from this, if someone could please point out how to do this, I'd greatly appreciate it.
Quite late, but for future readers here is how I do it.
In onStart() I register a broadcast receiver for the ACTION_USB_DEVICE_DETACHED action.
#Override
protected void onStart() {
Log.d(TAG, "onStart()");
super.onStart();
// Catch a USB detach broadcast intent.
detachReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
jobsDone();
}
}
};
// Set the intent filter for the broadcast receiver, and register.
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(detachReceiver, filter);
}
In my jobsDone() I just finish the Activity which is basically the same as pressing "back".
private void jobsDone() {
Log.d(TAG, "jobsDone()");
this.finish();
}
Since in my case only one USB device can be attached at one single time I do not have to bother with device_filter.xml for the detach.
Also remember to unregister the receiver.
#Override
protected void onStop() {
Log.d(TAG, "onStop()");
super.onStop();
// Unregister the BroadcastReceiver
unregisterReceiver(detachReceiver);
}

Categories

Resources