It is possible to change the Bluetooth device name using BluetoothAdapter.getDefaultAdapter().setName() in Android, but I am unable to find how we can do it in Flutter. I've tried using the flutter_blue package; however, I don't see how we can achieve it.
Thanks in advance!
// BT Rename
//
final String sNewName = "Syntactics";
final BluetoothAdapter myBTAdapter = BluetoothAdapter.getDefaultAdapter();
final long lTimeToGiveUp_ms = System.currentTimeMillis() + 10000;
if (myBTAdapter != null)
{
String sOldName = myBTAdapter.getName();
if (sOldName.equalsIgnoreCase(sNewName) == false)
{
final Handler myTimerHandler = new Handler();
myBTAdapter.enable();
myTimerHandler.postDelayed(
new Runnable()
{
#Override
public void run()
{
if (myBTAdapter.isEnabled())
{
myBTAdapter.setName(sNewName);
if (sNewName.equalsIgnoreCase(myBTAdapter.getName()))
{
Log.i(TAG_MODULE, "Updated BT Name to " + myBTAdapter.getName());
myBTAdapter.disable();
}
}
if ((sNewName.equalsIgnoreCase(myBTAdapter.getName()) == false) && (System.currentTimeMillis() < lTimeToGiveUp_ms))
{
myTimerHandler.postDelayed(this, 500);
if (myBTAdapter.isEnabled())
Log.i(TAG_MODULE, "Update BT Name: waiting on BT Enable");
else
Log.i(TAG_MODULE, "Update BT Name: waiting for Name (" + sNewName + ") to set in");
}
}
} , 500);
}
}
Related
I am making an app that has both a scanning and advertising functionality as I want to conduct some BLE experiments. But most of the time during the scan I get the device name and UUID as null and there are just flashes for when I am able to see the device that I am advertising with.
The scan feature works fine when I use an app like LightBlue because it constantly shows up in the scan window and the advertisement feature also seems to work fine when I start a scan using the LightBlue app so it is confusing me about what is causing the problem.
I want the scanning feature to detect the device as fast as it can, connect to it and return the details like timestamp, RSSI value etc. of the signal so I can use those values for my experiment. What changes should I do to my following code in order to do that with accuracy?
Here is the advertisement code:
final BluetoothManager bluetoothManagerAdv = (BluetoothManager) getSystemService( Context.BLUETOOTH_SERVICE);
if (bluetoothManagerAdv != null) {
mBluetoothAdapterAdv = bluetoothManagerAdv.getAdapter();
}
mBluetoothAdapterAdv.setName ( "BLE Experiment" );
mBluetoothLeAdvertiser = mBluetoothAdapterAdv.getBluetoothLeAdvertiser();
AdvertisingSetParameters parameters = new AdvertisingSetParameters.Builder().setInterval(AdvertisingSetParameters.INTERVAL_HIGH).setTxPowerLevel(AdvertisingSetParameters.TX_POWER_HIGH)
.setConnectable(true).build();
AdvertiseData data = new AdvertiseData.Builder()
.setIncludeDeviceName(false)
.build();
mAdvertiseCallback = new AdvertisingSetCallback () {
#Override
public void onAdvertisingSetStarted(AdvertisingSet advertisingSet,
int txPower,
int status) {
super.onAdvertisingSetStarted (advertisingSet, txPower, status);
}
#Override
public void onAdvertisingSetStopped(AdvertisingSet advertisingSet) {
Log.e(TAG, "Advertising onStartFailure: ");
super.onAdvertisingSetStopped (advertisingSet);
}
};
mBluetoothLeAdvertiser.startAdvertisingSet(parameters, data, null,null,null, mAdvertiseCallback);
And the scan code:
mIsScanning = true;
ScanSettings.Builder builderScanSettings = new ScanSettings.Builder();
builderScanSettings.setScanMode(ScanSettings.SCAN_MODE_BALANCED);
mBluetoothLeScanner.startScan(null, builderScanSettings.build(), scanCallback);
} else {
enableScanBtn();
mIsScanning = false;
mBluetoothLeScanner.stopScan(scanCallback);
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private final ScanCallback scanCallback = new ScanCallback () {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult ( callbackType, result );
if (mList.size () > 0) {
try {
mList.clear ();
mArrayAdapter.clear ();
mArrayAdapter.notifyDataSetChanged ();
rssi = result.getRssi ();
id = Arrays.toString(result.getDevice ().getUuids ());
} catch (final Exception e) {
e.printStackTrace ();
}
}
if (result == null || result.getDevice () == null) {
Log.e ( TAG, "-> No devices found" );
return;
}
try {
name = result.getDevice ().getName ();
time= System.currentTimeMillis();
String apDetails = "AP: " + name + "\n" +
"UUID: " + id + "\n" +
"RSSI: " + rssi + "\n" +
"Time : " + time;
Log.i ( TAG, apDetails );
mList.add ( apDetails );
} catch (NullPointerException e) {
Log.e ( TAG, e.getMessage () );
}
mArrayAdapter = new ArrayAdapter<> ( getApplicationContext (),
android.R.layout.simple_list_item_1, mList );
mListView.setAdapter ( mArrayAdapter );
If you want to see the complete code in the activity : here is the link
I am using BluetoothAdapter.LeScanCallback to scan for BLE devices. Once I get the required scanned data, I would like to display it on a textview. However, the textview is not updated with the scanned data. Appreciate if anyone could help on this.
private TextView TV_uuid;
private TextView TV_major;
private TextView TV_minor;
//Find BLE devices
private Runnable scanRunnable = new Runnable() {
#Override
public void run() {
if (isScanning) {
if (btAdapter != null) {
btAdapter.stopLeScan(leScanCallback);
}
} else {
if (btAdapter != null) {
btAdapter.startLeScan(leScanCallback);
}
}
isScanning = !isScanning;
scanHandler.postDelayed(this, scan_interval_ms);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TV_uuid = (TextView)findViewById(R.id.tv_uuid2);
TV_major = (TextView)findViewById(R.id.tv_major2);
TV_minor = (TextView)findViewById(R.id.tv_minor2);
//start scan BLE
scanHandler.post(scanRunnable);
}
private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice bluetoothDevice, final int rssi, final byte[] scanData) {
if (scanData[7] == 0x02 && scanData[8] == 0x15) { // iBeacon indicator
UUID uuid = getGuidFromByteArray(Arrays.copyOfRange(scanData, 9, 25));
int major = (scanData[25] & 0xff) * 0x100 + (scanData[26] & 0xff);
int minor = (scanData[27] & 0xff) * 0x100 + (scanData[28] & 0xff);
byte txpw = scanData[29];
Log.i(TAG, "iBeacon Major = " + major + " | Minor = " + minor + " TxPw " + (int)txpw + " | UUID = " + uuid.toString());
TV_uuid.setText(uuid.toString());
TV_major.setText(major);
TV_minor.setText(minor);
}
}
};
If I remember correctly, that callback runs on a separate thread, so you shouldn't put view updates in the callback directly. If you just want to test, you can wrap the view updates inside a runOnUiThread() call and see if that works.
runOnUiThread(new Runnable(){
public void run(){
//set the value of your textviews here
}
}
}
Ideally though you should be decouple the scanning from the Activity. I'd put BLE scanning code inside a service that is either bound by a client Activity, or sends update to listening clients using LiveData / local broadcast manager.
Probably if (scanData[7] == 0x02 && scanData[8] == 0x15) is preventing the code to execute. Or you forgot to start the scan and install the onLeScanCallback listener
i want to search and listing bluetooth devices in android, my program now able to list all the active devices but not able to send pairing request to the other devices .I want to implement this onItemClick of list element.And also if bluetooth is not enabled of my device then show a permission to active device,if i go for yes then ok,but if i go for no then permission show again until i press yes..how can i do this?plz help with code..here is my code..
public class Main extends Activity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter;
private ArrayList<BluetoothDevice> btDeviceList = new ArrayList<BluetoothDevice>();
private ArrayList<String> mylist= new ArrayList<String>();
private ListView lv;
private Button btn;
public Parcelable[] uuidExtra;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void search(View view)
{
//Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_UUID);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(ActionFoundReceiver, filter); // Don't forget to unregister during onDestroy
// Getting the Bluetooth adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
Toast.makeText(getApplicationContext(),"\nAdapter: " + btAdapter,5000).show();
CheckBTState();
}
private void setDeviceList(ArrayList<String> list) {
lv = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
}
/* This routine is called when an activity completes.*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
CheckBTState();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (btAdapter != null) {
btAdapter.cancelDiscovery();
}
unregisterReceiver(ActionFoundReceiver);
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// If it isn't request to turn it on
// List paired devices
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
Toast.makeText(getApplicationContext(),"\nBluetooth NOT supported. Aborting.",5000).show();
return;
} else {
if (btAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(),"\nBluetooth is enabled...",5000).show();
// Starting the device discovery
btAdapter.startDiscovery();
} else if (!btAdapter.isEnabled()){
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
/* else{
Intent intent = new Intent(btAdapter.ACTION_STATE_CHANGED);
startActivityForResult(intent, RESULT_CANCELED);
}*/
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){
#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);
Toast.makeText(getApplicationContext(),"\n Device: " + device.getName() + ", " + device,5000).show();
mylist.add(device.getName());
setDeviceList(mylist);
} else {
if(BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
for (int i=0; i<uuidExtra.length; i++) {
Toast.makeText(getApplicationContext(),"\n Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString(),5000).show();
}
} else {
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(getApplicationContext(),"\nDiscovery Started...",5000).show();
} else {
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(getApplicationContext(),"\nDiscovery Finished",5000).show();
Iterator<BluetoothDevice> itr = btDeviceList.iterator();
while (itr.hasNext()) {
// Get Services for paired devices
BluetoothDevice device = itr.next();
Toast.makeText(getApplicationContext(),"\nGetting Services for " + device.getName() + ", " + device,5000).show();
if(!device.fetchUuidsWithSdp()) {
Toast.makeText(getApplicationContext(),"\nSDP Failed for " + device.getName(),5000).show();
}
}
}
}
}
}
}
};
}
It's too late but here is code -> You need to use background thread to connect with bluetooth device as a client. and UUID is Universal Uniquely identification you can use online UUID generator. for secure connections and then get socket with device and connect with it;
ConnectWithDevice(context : ConnectWithBluetooth, device : BluetoothDevice) : Thread(){
private val mContext : ConnectWithBluetooth = context
private val mmSocket : BluetoothSocket
private val mmDevice : BluetoothDevice
// Default UUID
private val mmDefaultUUID = UUID.fromString("78c374fd-f84d-4a9e-aa5b-9b0b6292952e")
init {
var temp : BluetoothSocket? = null
mmDevice = device
try {
// Try here device.createInsecureConnect if it's work then start with this;
temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)
}catch (en : NullPointerException){
en.printStackTrace()
// Try here device.createInsecureConnect if it's work then start with this;
temp = device.createRfcommSocketToServiceRecord(mmDefaultUUID)
}catch (e : IOException){
e.printStackTrace()
Log.e("TAG","Socket's create() method failed",e)
}
mmSocket = temp!!
Log.i("TAG","Got the Socket")
}
override fun run() {
// Cancel discovery because it otherwise slows down the connection.
if(mContext.bluetoothAdapter != null){
mContext.bluetoothAdapter!!.cancelDiscovery()
}
try{
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
Log.i("TAG","Connecting...")
mmSocket.connect()
Log.i("TAG","Bluetooth Successfully Connected")
}catch (connectException : IOException){
// Unable to connect; close the socket and return.
try{
mmSocket.close()
}catch (closeException : IOException){
Log.e("TAG","Could not close the client socket",closeException)
}
return
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
Log.i("TAG","Device is Connected")
//manageMyConnectedSocket(mmSocket)
}
// Closes the client socket and causes the thread to finish.
// Call this method from the main activity to shut down the connection.
fun cancel(){
try {
mmSocket.close()
} catch (e: IOException) {
Log.e(ContentValues.TAG, "Could not close the client socket", e)
}
}
}
As I'm currently working on a little bluetooth library for Android, I'm trying to get all the service uuids of the devices I discovered in my surrounding.
When my broadcast receiver gets the BluetoothDevice.ACTION_FOUND intent, I'm extracting the device and call:
device.fetchUuidsWithSdp();
This will result BluetoothDevice.ACTION_UUID intents for each device found and I'm handling them with the same receiver:
BluetoothDevice d = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
if(uuidExtra == null) {
Log.e(TAG, "UUID = null");
}
if(d != null && uuidExtra != null)
Log.d(TAG, d.getName() + ": " + uuidExtra.toString());
The thing is, that uuidExtra is always null.
How can i get all the UUIDs of the surrounding devices?
EDIT:
Im working on a Nexus 7. I tried code i found on the internet and this also gives me a NullPointerException: http://digitalhacksblog.blogspot.de/2012/05/android-example-bluetooth-discover-and.html
Thank you.
The documentation on this states...
Always contains the extra field BluetoothDevice.EXTRA_UUID
However, just like you, I have found this not to be true.
If you call fetchUuidsWithSdp() while device discovery is still taking place BluetoothDevice.EXTRA_UUID can be null.
You should wait until you receive BluetoothAdapter.ACTION_DISCOVERY_FINISHED before you make any calls to fetchUuidsWithSdp().
NOTE: This solution applies to CLASSIC bluetooth and not BLE. For BLE check how to send
manufacturer specific Data in advertiser on the peripheral side
The problem with fetching Uuids is that you have only one bluetooth adapter, and we cannot have parallel api calls which uses adapter for its purpose.
As Eddie pointed out, wait for BluetoothAdapter.ACTION_DISCOVERY_FINISHED and then call fetchUuidsWithSdp().
Still this cannot guarantee uuids to be fetched for all devices. In addition to this one must wait for each subsequent call to fetchuuidsWithSdp() to complete, and then give a call to this method for another device.
See the code below --
ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
} 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();
}
} else if (BluetoothDevice.ACTION_UUID.equals(action)) {
// This is when we can be assured that fetchUuidsWithSdp has completed.
// So get the uuids and call fetchUuidsWithSdp on another device in list
BluetoothDevice deviceExtra = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
System.out.println("DeviceExtra address - " + deviceExtra.getAddress());
if (uuidExtra != null) {
for (Parcelable p : uuidExtra) {
System.out.println("uuidExtra - " + p);
}
} else {
System.out.println("uuidExtra is still null");
}
if (!mDeviceList.isEmpty()) {
BluetoothDevice device = mDeviceList.remove(0);
boolean result = device.fetchUuidsWithSdp();
}
}
}
}
UPDATE: Latest android versions (mm & above) would result in triggering a pairing process with each device
Here is a good example of how to get UUIDs of service characteristics from a service that I did for getting heart rate devices:
private class HeartRateBluetoothGattCallback extends BluetoothGattCallback {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
logMessage("CONNECTED TO " + gatt.getDevice().getName(), false, false);
gatt.discoverServices();
} else if(newState == BluetoothProfile.STATE_DISCONNECTED) {
logMessage("DISCONNECTED FROM " + gatt.getDevice().getName(), false, false);
if(mIsTrackingHeartRate)
handleHeartRateDeviceDisconnection(gatt);
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
logMessage("DISCOVERING SERVICES FOR " + gatt.getDevice().getName(), false, false);
if(mDesiredHeartRateDevice != null &&
gatt.getDevice().getAddress().equals(mDesiredHeartRateDevice.getBLEDeviceAddress())) {
if(subscribeToHeartRateGattServices(gatt)) {
mIsTrackingHeartRate = true;
setDeviceScanned(getDiscoveredBLEDevice(gatt.getDevice().getAddress()), DiscoveredBLEDevice.CONNECTED);
broadcastHeartRateDeviceConnected(gatt.getDevice());
} else
broadcastHeartRateDeviceFailedConnection(gatt.getDevice());
} else {
parseGattServices(gatt);
disconnectGatt(getDiscoveredBLEDevice(gatt.getDevice().getAddress()));
}
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
if(characteristic.getUuid().equals(UUID.fromString(HEART_RATE_VALUE_CHAR_READ_ID))) {
int flag = characteristic.getProperties();
int format = -1;
if ((flag & 0x01) != 0)
format = BluetoothGattCharacteristic.FORMAT_UINT16;
else
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Integer heartRateValue = characteristic.getIntValue(format, 1);
if(heartRateValue != null)
broadcastHeartRateValue(heartRateValue);
else
Log.w(SERVICE_NAME, "UNABLE TO FORMAT HEART RATE DATA");
}
};
};
private void parseGattServices(BluetoothGatt gatt) {
boolean isHeartRate = false;
for(BluetoothGattService blueToothGattService : gatt.getServices()) {
logMessage("GATT SERVICE: " + blueToothGattService.getUuid().toString(), false, false);
if(blueToothGattService.getUuid().toString().contains(HEART_RATE_DEVICE_SERVICE_CHARACTERISTIC_PREFIX))
isHeartRate = true;
}
if(isHeartRate) {
setDeviceScanned(getDiscoveredBLEDevice(gatt.getDevice().getAddress()), DiscoveredBLEDevice.IS_HEART_RATE);
broadcastHeartRateDeviceFound(getDiscoveredBLEDevice(gatt.getDevice().getAddress()));
} else
setDeviceScanned(getDiscoveredBLEDevice(gatt.getDevice().getAddress()), DiscoveredBLEDevice.NOT_HEART_RATE);
}
private void handleHeartRateDeviceDisconnection(BluetoothGatt gatt) {
broadcastHeartRateDeviceDisconnected(gatt.getDevice());
gatt.close();
clearoutHeartRateData();
scanForHeartRateDevices();
}
private void disconnectGatt(DiscoveredBLEDevice device) {
logMessage("CLOSING GATT FOR " + device.getBLEDeviceName(), false, false);
device.getBlueToothGatt().close();
device.setBlueToothGatt(null);
mInDiscoveryMode = false;
}
private boolean subscribeToHeartRateGattServices(BluetoothGatt gatt) {
for(BluetoothGattService blueToothGattService : gatt.getServices()) {
if(blueToothGattService.getUuid().toString().contains(HEART_RATE_DEVICE_SERVICE_CHARACTERISTIC_PREFIX)) {
mHeartRateGattService = blueToothGattService;
for(BluetoothGattCharacteristic characteristic : mHeartRateGattService.getCharacteristics()) {
logMessage("CHARACTERISTIC UUID = " + characteristic.getUuid().toString(), false, false);
for(BluetoothGattDescriptor descriptor :characteristic.getDescriptors()) {
logMessage("DESCRIPTOR UUID = " + descriptor.getUuid().toString(), false, false);
}
if(characteristic.getUuid().equals(UUID.fromString(HEART_RATE_VALUE_CHAR_READ_ID))) {
gatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(HEART_RATE_VALUE_CHAR_DESC_ID));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
return gatt.writeDescriptor(descriptor);
}
}
break; //break out of master for-loop
}
}
return false;
}
I suppose you need to be paired with the device in order to receive the uuids.
At least, this is what happened to me.
device.getUuids() use this to get all the uuid of that paired device in the form of ParcelUuid; Example code below:-
private void get_uuid_from_paired_devices(){
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device: pairedDevices){
for (ParcelUuid uuid: device.getUuids()){
String uuid_string = uuid.toString();
Log.d(TAG, "uuid : "+uuid_string);
}
}
}
Below worked for me to fetch the records from the remote device
-0-
registerReceiver(..,
new IntentFilter(BluetoothDevice.ACTION_UUID));
-1-
device.fetchUuidsWithSdp();
-2-from within the broadcase receiver
if (BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuids = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
for (Parcelable ep : uuids) {
Utilities.print("UUID records : "+ ep.toString());
}
}
You can also fetch the offline cached UUID records with
BluetoothDevice.getUuids();
I am trying to measure the wifi signal strength 5 times (after every second) & display it in a TextView. I simultaneously write it to external storage as well. Everything runs fine except that I am NOT able to see the results in real time. The app would run for 5 secs with a blank screen and then show up the results (which are correct btw, i.e 5 different readings after each second).
I'd want to see the results updating as soon the new value is calculated in each iteration of the for loop.
Thanks
Here is the code
public class WifiDemo extends Activity implements OnClickListener {
private static final String TAG = "WiFiDemo";
WifiManager wifi;
TextView textStatus;
Button buttonScan;
/** Called when the activity is first created. */
/*
* (non-Javadoc)
*
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setup UI
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
// Setup WiFi
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Get WiFi status
runOnUiThread(new Runnable() {
public void run() {
try {
FileWriter fw = new FileWriter(
Environment.getExternalStorageDirectory()
+ "/bluetooth/wifi.txt");
for (int i = 0; i < 5; i++) {
WifiInfo info = wifi.getConnectionInfo();
Date d = new Date(System.currentTimeMillis());
String stat = "\n\nWiFi Status: " + info.getRssi()
+ " " + d.getHours() + ":" + d.getMinutes()
+ ":" + d.getSeconds();
textStatus.append(stat);
fw.write(stat);
fw.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
textStatus.append("something wrong");
}
}
});
}
}
}
You can try to create a handler to handle UI update tasks in the main thread. Do not update UI in your thread, instead, do it by passing handler messages to make sure this job is handled in the main thread. It works fine for me. I've modified some of your code here (I removed the write file part),
public class WifiDemo extends Activity implements OnClickListener {
private static final String TAG = "WiFiDemo";
private static final int WifiDetectStart = 0;
private static final int WifiDetectStop = 1;
private String stat;
WifiManager wifi;
TextView textStatus;
Button buttonScan;
Handler handler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setup UI
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
//setup handler
handler = new Handler(){
#Override
public void handleMessage(Message msg) {
if(msg.what == WifiDetectStart)
{
textStatus.append(stat);
}
if(msg.what == WifiDetectStop)
{
Thread.currentThread().interrupt();
}
super.handleMessage(msg);
}
};
// Setup WiFi
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Get WiFi status
Thread myThread = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
WifiInfo info = wifi.getConnectionInfo();
Date d = new Date(System.currentTimeMillis());
stat = "\n\nWiFi Status: " + info.getRssi()
+ " " + d.getHours() + ":" + d.getMinutes()
+ ":" + d.getSeconds();
Message msg = new Message();
msg.what = WifiDetectStart;
handler.sendMessage(msg);
// textStatus.append(stat);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//finish this operation
Message msg = new Message();
msg.what = WifiDetectStop;
handler.sendMessage(msg);
}
});
myThread.start();
}
}
The problem is you're doing something right by trying to do your updating in a separate Runnable... however, your Runnable is running in the UI thread and therefore causing the UI thread to sit in the loop (including the Thread.sleep()). You're not getting your updates because you're causing the UI to wait on you.
If your processing is reasonably heavy, you might wish to break it out into a separate thread and send messages to a handler. Otherwise, it might be easiest to do something like the following (untested, but something similar):
if (Environment.MEDIA_MOUNTED.equals(state)) {
textStatus.postDelayed(new Runnable() {
public void run() {
WifiInfo info = wifi.getConnectionInfo();
Date d = new Date(System.currentTimeMillis());
String stat = "\n\nWiFi Status: " + info.getRssi()
+ " " + d.getHours() + ":" + d.getMinutes()
+ ":" + d.getSeconds();
textStatus.append(stat);
// relaunch if we're not through with our number of iterations.
// mCount is a new field.
if(mCount++ < 5) {
textStatus.postDelayed(this, 1000);
}
}
}, 1000);
}