Same as this question and many others from a few years ago:
how to turn speaker on/off programmatically in android 4.0
It seems that Android has changed the way it handles this.
here are the things I tried to make an Outgoing call to have a speakerphone programmatically. None of these solutions worked for me on Android Pie.
while they seem to work well on Android Nougat and Oreo
Solution 1.
final static int FOR_MEDIA = 1;
final static int FORCE_NONE = 0;
final static int FORCE_SPEAKER = 1;
Class audioSystemClass = Class.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);
2.
AudioManager audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(true);
3.
AudioManager audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
4.
Thread thread = new Thread() {
#Override
public void run() {
try {
while(true) {
sleep(1000);
audioManager.setMode(AudioManager.MODE_IN_CALL);
if (!audioManager.isSpeakerphoneOn())
audioManager.setSpeakerphoneOn(true);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
the app has the following permissions granted among many others:
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
I have also tried the following solution only for outgoing calls. and it also didn't work.
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.putExtra("speaker", true);
callIntent.setData(Uri.parse("tel:" + number));
context.startActivity(callIntent);
In Android Pie, I had the same problem. I resolved it using an InCallService with
setAudioRoute(ROUTE_SPEAKER)
Your app needs to be Default phone app.
I am surprised nobody mentioned TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE.
As an intent:
val uri = Uri.fromParts("tel", PHONE_NUMBER, null)
val intentCall = Intent(Intent.ACTION_CALL, uri).apply {
putExtra(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, true)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
startActivity(intentCall)
Using TelecomManager.placeCall:
val uri = Uri.fromParts("tel", PHONE_NUMBER, null)
val extras = Bundle().apply { putBoolean(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, true) }
val telecomManager = getSystemService(TELECOM_SERVICE) as TelecomManager
telecomManager.placeCall(uri, extras)
The default phone app should handle that extra data and enable the speakers.
Remember to ask for android.permission.CALL_PHONE permission.
in my self managed voice calling app I managed by changing connection service audio route like below beside using audioManager,
public void setSpeakerphoneOn(final boolean enabled) {
if (enabled != audioManager.isSpeakerphoneOn()) {
Log.d(TAG, "setSpeakerphoneOn(): " + enabled);
audioManager.setSpeakerphoneOn(enabled);
}
}
and in my connectionservice class,
public void speakerOnOff(String uuid,boolean on) {
Log.d(TAG,"SPEAKER is" + String.valueOf(on));
Connection connection = VoipConnectionService.getConnection(uuid);
if (on) {
connection.setAudioRoute(CallAudioState.ROUTE_SPEAKER);
} else {
connection.setAudioRoute(CallAudioState.ROUTE_EARPIECE);
}
}
or you can change route according to your audio device for output
public void speakerOnOff(String uuid,String device) {
Log.d(TAG,"Device to route is" + device);
Connection connection = VoipConnectionService.getConnection(uuid);
int state = CallAudioState.ROUTE_EARPIECE ;
switch (device){
case "SPEAKER_PHONE":
state = CallAudioState.ROUTE_SPEAKER ;
break;
case "WIRED_HEADSET":
state = CallAudioState.ROUTE_WIRED_HEADSET ;
break;
case "EARPIECE" :
case "NONE" :
state = CallAudioState.ROUTE_EARPIECE ;
break;
case "BLUETOOTH" :
state = CallAudioState.ROUTE_BLUETOOTH ;
break;
}
connection.setAudioRoute(state);
}
For this problem please try the following code it is working for me.
AudioManager myAudioManager;
myAudioManager.setMode(AudioManager.MODE_NORMAL);
myAudioManager.setSpeakerphoneOn(true);
Related
I am attempting to implement a Loud Speaker / Earpiece switch in Android 12 using the new AudioManager.setCommunicationDevice in place of the deprecated AudioManager.setSpeakerphoneOn.
The result of the set call is true, but the device does not appear to update (both functionally and by checking AudioManager.getCommunicationDevice before and after).
The application is selected as the default Phone package, AudioManager mode is set to AudioManager.MODE_IN_CALL and the manifest includes
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
Below is a code snippet which shows the effect of trying to just set loud speaker during an active call.
AudioDeviceInfo loudSpeakerAudioDevice = null;
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_CALL);
List<AudioDeviceInfo> audioDevices = audioManager.getAvailableCommunicationDevices();
for (AudioDeviceInfo audioDevice : audioDevices)
{
if (audioDevice.getType() == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER)
{
loudSpeakerAudioDevice = audioDevice;
}
}
Log.i("Demo", "Current AudioDevice = " + audioManager.getCommunicationDevice().toString());
if (audioManager.getCommunicationDevice().getType() == AudioDeviceInfo.TYPE_BUILTIN_EARPIECE)
{
Log.i("Demo", "Setting to loudSpeakerAudioDevice = " + loudSpeakerAudioDevice.toString());
if (audioManager.setCommunicationDevice(loudSpeakerAudioDevice) == false)
{
Log.e("Demo", "Failed to set audio device");
}
Log.i("Demo", "New AudioDevice = " + audioManager.getCommunicationDevice().toString());
}
The output of this shows the device ID is the same before and after the set (21).
2022-07-27 10:30:01.465 27907-27907/? I/Demo: Current AudioDevice = android.media.AudioDeviceInfo#21
2022-07-27 10:30:01.501 27907-27907/? I/Demo: Setting to loudSpeakerAudioDevice = android.media.AudioDeviceInfo#22
2022-07-27 10:30:01.518 27907-27907/? I/Demo: New AudioDevice = android.media.AudioDeviceInfo#21
I am struggling on how to capture the audio stream from connected USB microphone. I have tried to use the MediaCapture with MediaRecorder.AudioSource.MIC as source which worked but recording quality isn't quite usable for me and you can't be sure if the audio source is really USB or the built in device microphone. What I need is to use the USB audio feature but so far I am unable to make any progress.
To use third-party libraries is overkill for me since I need to only receive the stream of audio data from the microphone, the rest of the processing is already done and working, only the audio source is the issue.
What I need to do is:
Check if there is USB microphone connected to the device.
Find out what characteristics this device has (supported sampling rates, channels etc.)
Record audio data
What I've done so far:
Generate a list of connected USB device which class is UsbConstants.USB_CLASS_AUDIO
private static final String ACTION_USB_PERMISSION = PACKAGE_NAME + ".USB_PERMISSION";
private UsbManager mUsbManAndroid;
private Map<String, UsbDevice> mAndroidDeviceMap;
private PendingIntent mPermissionIntent;
private ArrayList<UsbDeviceListItem> getUSBDevicesList() {
// Enumerate USB devices
mAndroidDeviceMap = mUsbManAndroid.getDeviceList();
ArrayList<UsbDeviceListItem> usbDevicesList = new ArrayList<>();
for (String key : mAndroidDeviceMap.keySet()) {
UsbDevice device = mAndroidDeviceMap.get(key);
// Check the device class
if (device.getDeviceClass() == UsbConstants.USB_CLASS_AUDIO) {
usbDevicesList.add(usbDeviceToListItem(key, device));
} else if (device.getDeviceClass() == UsbConstants.USB_CLASS_PER_INTERFACE) {
UsbInterface interface;
for (int i = 0; i < device.getInterfaceCount(); i++) {
// Check if at least one interface is audio
interface = device.getInterface(i);
if (interface != null && interface.getInterfaceClass() == UsbConstants.USB_CLASS_AUDIO) {
usbDevicesList.add(usbDeviceToSysBusUsbDevice(key, device));
break;
}
}
}
}
/////////////////////////////////////////////////////////
// Here goes some code to identify the device using
// linux shell commands if device SDK version is older
// than 21 (Lollipop). In older versions of Android
// we can't get device's Vendor and Device names using
// Android API, we need to use some linux shell commands.
/////////////////////////////////////////////////////////
return usbDevicesList;
}
Request permission for selected usb device from the list:
mUsbDeviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
UsbDeviceListItem usbDeviceItem = (UsbDeviceListItem) mUsbDeviceList.getItemAtPosition(i);
UsbDevice device = mAndroidDeviceMap.get(usbDeviceItem.getDevicePath());
manager.requestPermission(device, mPermissionIntent);
}
});
Permission broadcast receiver:
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 = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
streamFromUsbDevice(device)
}
}
else {
Toast.makeText(SensorActivity.this, "Permission denied for device " + device,
Toast.LENGTH_SHORT).show();
}
}
}
}
};
Sample method for reading data from the USB device
private void streamFromUSBDevice(UsbDevice device) {
UsbEndpoint endpoint;
UsbInterface usbInterface;
////////////////////////////////////////////////////////////////
// Here was code for finding the first audio interface with its
// endpoint. But because I failed to make it work I was manually
// getting them by index.
////////////////////////////////////////////////////////////////
usbInterface = device.getInterface(2);
endpoint = usbInterface.getEndpoint(0);
if (endpoint == null) {
Log.i(TAG, getString(R.string.endpoint_not_found));
notifyUser(R.string.endpoint_not_found);
return;
}
Log.i(TAG, R.string.connecting_to_usb_device);
notifyUser(R.string.connecting_to_usb_device);
UsbDeviceConnection connection = manager.openDevice(device);
connection.claimInterface(usbInterface, true);
while (true) {
if (!isRecording) {
// Close the connection to the usb device
connection.close();
notifyUser(R.string.status_idle);
break;
}
UsbRequest request = new UsbRequest();
request.initialize(connection, endpoint);
byte[] buffer = new byte[endpoint.getMaxPacketSize()];
final ByteBuffer buf = ByteBuffer.wrap(buffer);
Log.i(TAG, "Requesting queue...");
if (!request.queue(buf, buffer.length)) {
Log.e(TAG, getString(R.string.error_queue_request)));
notifyUser(R.string.error_queue_request);
isRecording = false;
break;
}
Log.i(TAG, "Requesting response...");
final UsbRequest response = connection.requestWait();
if (response == null) {
Log.e(TAG, "Null response!");
notifyUser(R.string.null_response);
isRecording = false;
break;
}
final int nRead = buf.position();
if (nRead > 0) {
Log.i(TAG, "Streaming " + nRead + " bytes to UI");
Bundle args = new Bundle();
args.putShortArray(ARG_RECORDED_DATA, byte2short(buffer));
sendMessageToUI(SHOW_AUDIO_DATA_PACKET, args, null);
} else {
Log.e(TAG, "No data in buffer!");
notifyUser(R.string_empty_buffer);
isRecording = false;
break;
}
}
}
What I am getting from this is that request.queue() is always returning false.
I have also attempted to use the connection.bulkTransfer(endpoint, buffer, buffer.length, 0); method but the result is always -1.
If someone was in similar situation please help.
P.S. The error I am receiving in the log is: UsbRequestJNI: request is closed in native_queue.
I am writing an android app for Recording Audio from Blue tooth, but I Unable to record Audio via Blue tooth in Android.
You can see below the code
AudioManager am;
am = (AudioManager) getSystemService(AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.startBluetoothSco();
am.setBluetoothScoOn(true);
Intent intent = getIntent();
if (intent.getBooleanExtra("privacy", false)) {
showServerPrompt(true);
return;
}
// If the Ringdroid media select activity was launched via a
// GET_CONTENT intent, then we shouldn't display a "saved"
// message when the user saves, we should just return whatever
// they create.
mWasGetContentIntent = intent.getBooleanExtra(
"was_get_content_intent", false);
mFilename = intent.getData().toString();
mSoundFile = null;
mKeyDown = false;
if (mFilename.equals("record")) {
try {Intent recordIntent = new Intent(
MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(recordIntent, REQUEST_CODE_RECORD);
} catch (Exception e) {
showFinalAlert(e, R.string.record_error);
}
}
mHandler = new Handler();
loadGui();
mHandler.postDelayed(mTimerRunnable, 100);
if (!mFilename.equals("record")) {
loadFromFile();
}
}
This works well when using the phone in a normal fashion. However, it does not detect the presence of a bluetooth headset and still uses the phone's own microphone even when the headset is plugged in.
working code below
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
Log.d(TAG, "Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
/*
* Now the connection has been established to the bluetooth device.
* Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
* new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
* AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
*
* After finishing, don't forget to unregister this receiver and
* to stop the bluetooth connection with am.stopBluetoothSco();
*/
unregisterReceiver(this);
}
}
}, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));
Log.d(TAG, "starting bluetooth");
am.startBluetoothSco();
I have the BleFindMeClient working on the HTC 1X+ in conjunction with the TI Mini Keyfob. I'm trying to extend it slightly to read the battery level (not register for battery updates). I can do it from the BTool, but my Android prog fails, and I get the debug message:
getCharacteristic - Service data not found
What does this mean? And where would I find out what this and other error messages mean?
Clearly I can write characteristics because I can set the alarm. But there is something rather basic that I have not grasped about reading characteristics, but I can't find example code.
Could someone throw me a better code fragment please, or spot something dumb in the following?
public class BatteryProfileClient extends BleClientProfile {
private static String TAG = "BatteryProfileClient";
static public BleGattID myUuid = new BleGattID("0000180f-0000-1000-8000-00805f9b34fb");
private static final BleGattID BATTERY_CHARACTERISTIC = new BleGattID("00002a19-0000-1000-8000-00805f9b34fb");
private BatteryServiceClient mBatteryServiceClient = new BatteryServiceClient();
public BatteryProfileClient(Context context) {
super(context, myUuid);
Log.d(TAG, "Instantiated");
ArrayList<BleClientService> services = new ArrayList<BleClientService>();
services.add(mBatteryServiceClient);
init(services, null);
}
public void batt(BluetoothDevice device) {
BleCharacteristic battLevelCharacteristic = mBatteryServiceClient.getCharacteristic(device, BATTERY_CHARACTERISTIC);
byte b[] = battLevelCharacteristic.getValue();
Log.d(TAG, "battery " + b);
}
}
Dont know if im late, but that should solve your problem -
public int getbattery(BluetoothGatt mBluetoothGatt) {
BluetoothGattService batteryService = mBluetoothGatt
.getService(BATTERY_SERVICE_UUID);
if (batteryService == null) {
Log.d(TAG, "Battery service not found!");
return 0;
}
BluetoothGattCharacteristic batteryLevel = batteryService
.getCharacteristic(BATTERY_LEVEL_UUID);
if (batteryLevel == null) {
Log.d(TAG, "Battery level not found!");
return 0;
}
mBluetoothGatt.readCharacteristic(batteryLevel);
return batteryLevel.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT8, 0);
}
Visit https://stackoverflow.com/questions/19539535/how-to-get-the-battery-level-after-connect-to-the-ble-device
same problem
use BluetoothGattCallback
for callBack and read Battery Value
How can I list all connected bluetooth devices on android ?
thanks!
public void checkConnected()
{
// true == headset connected && connected headset is support hands free
int state = BluetoothAdapter.getDefaultAdapter().getProfileConnectionState(BluetoothProfile.HEADSET);
if (state != BluetoothProfile.STATE_CONNECTED)
return;
try
{
BluetoothAdapter.getDefaultAdapter().getProfileProxy(_context, serviceListener, BluetoothProfile.HEADSET);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private ServiceListener serviceListener = new ServiceListener()
{
#Override
public void onServiceDisconnected(int profile)
{
}
#Override
public void onServiceConnected(int profile, BluetoothProfile proxy)
{
for (BluetoothDevice device : proxy.getConnectedDevices())
{
Log.i("onServiceConnected", "|" + device.getName() + " | " + device.getAddress() + " | " + proxy.getConnectionState(device) + "(connected = "
+ BluetoothProfile.STATE_CONNECTED + ")");
}
BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy);
}
};
As of API 14 (Ice Cream), Android has a some new BluetoothAdapter methods including:
public int getProfileConnectionState (int profile)
where profile is one of HEALTH, HEADSET, A2DP
Check response, if it's not STATE_DISCONNECTED you know you have a live connection.
Here is code example that will work on any API device:
BluetoothAdapter mAdapter;
/**
* Check if a headset type device is currently connected.
*
* Always returns false prior to API 14
*
* #return true if connected
*/
public boolean isVoiceConnected() {
boolean retval = false;
try {
Method method = mAdapter.getClass().getMethod("getProfileConnectionState", int.class);
// retval = mAdapter.getProfileConnectionState(android.bluetooth.BluetoothProfile.HEADSET) != android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
retval = (Integer)method.invoke(mAdapter, 1) != 0;
} catch (Exception exc) {
// nothing to do
}
return retval;
}
First you need to retrieve the BluetoothAdapter:
final BluetoothAdapter btAdapter =
BluetoothAdapter.getDefaultAdapter();
Second you need to make sure Bluetooth is available and turned on :
if (btAdapter != null && btAdapter.isEnabled()) // null means no
Bluetooth!
If the Bluetooth is not turned out you can either use btAdapter.enable() which is not recommended in the documentation or ask the user to do it : Programmatically enabling bluetooth on Android
Third you need to define an array of states (to filter out
unconnected devices):
final int[] states = new int[] {BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.STATE_CONNECTING};
Fourth, you create a BluetoothProfile.ServiceListener which
contains two callbacks triggered when a service is connected and
disconnected :
final BluetoothProfile.ServiceListener listener = new BluetoothProfile.ServiceListener() {
#Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
}
#Override
public void onServiceDisconnected(int profile) {
}
};
Now since you have to repeat the querying process for all available Bluetooth Profiles in the Android SDK (A2Dp, GATT, GATT_SERVER, Handset, Health, SAP) you should proceed as follow :
In onServiceConnected, place a condition that check what is the current profile so that we add the found devices into the correct collection and we use : proxy.getDevicesMatchingConnectionStates(states) to filter out unconnected devices:
switch (profile) {
case BluetoothProfile.A2DP:
ad2dpDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.GATT: // NOTE ! Requires SDK 18 !
gattDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.GATT_SERVER: // NOTE ! Requires SDK 18 !
gattServerDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.HEADSET:
headsetDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.HEALTH: // NOTE ! Requires SDK 14 !
healthDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.SAP: // NOTE ! Requires SDK 23 !
sapDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
}
And finally, the last thing to do is start the querying process :
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.A2DP);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT_SERVER); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEADSET);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEALTH); // NOTE ! Requires SDK 14 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.SAP); // NOTE ! Requires SDK 23 !
source: https://stackoverflow.com/a/34790442/2715054
So you get the list of paired devices.
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevicesList = btAdapter.getBondedDevices();
for (BluetoothDevice pairedDevice : pairedDevicesList) {
Log.d("BT", "pairedDevice.getName(): " + pairedDevice.getName());
Log.d("BT", "pairedDevice.getAddress(): " + pairedDevice.getAddress());
saveValuePreference(getApplicationContext(), pairedDevice.getName(), pairedDevice.getAddress());
}
Android system doesn't let you query for all "currently" connected devices. It however, you can query for paired devices. You will need to use a broadcast receiver to listen to ACTION_ACL_{CONNECTED|DISCONNECTED} events along with STATE_BONDED event to update your application states to track what's currently connected.
I found a solution and it works on android 10
Kotlin
private val serviceListener: ServiceListener = object : ServiceListener {
var name: String? = null
var address: String? = null
var threadName: String? = null
override fun onServiceDisconnected(profile: Int) {}
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
for (device in proxy.connectedDevices) {
name = device.name
address = device.address
threadName = Thread.currentThread().name
Toast.makeText(
this#MainActivity,
"$name $address$threadName",
Toast.LENGTH_SHORT
).show()
Log.i(
"onServiceConnected",
"|" + device.name + " | " + device.address + " | " + proxy.getConnectionState(
device
) + "(connected = "
+ BluetoothProfile.STATE_CONNECTED + ")"
)
}
BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy)
}
}
Call this method in main thread
BluetoothAdapter.getDefaultAdapter()
.getProfileProxy(this, serviceListener, BluetoothProfile.HEADSET)
Java
original code
Please analyze this class online.
Here you will find how to discover all connected (paired) Bluetooth devices.
Well here are the steps:
First, you start intent to discover devices
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
Register a broadcast reciver for it:
registerReceiver(mReceiver, filter);
On the definition of mReceiver:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
arrayadapter.add(device.getName())//arrayadapter is of type ArrayAdapter<String>
lv.setAdapter(arrayadapter); //lv is the list view
arrayadapter.notifyDataSetChanged();
}
}
and the list will be automatically populated on new device discovery.