简体   繁体   中英

How to extract Bluetooth Scan Results from intent?

How would someone extract Scan Results from an intent object in C#?

I am having a callback class that derives from BroadcastReceiver. In the same class I have this override method that I am getting scanned bluetooth devices.

public override void OnReceive(Context context, Intent intent)
{
   BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice)
}

I need to know if there is way to extract ScanResults from that intent object so I can convert those ScanResults to byte[] and start parsing the information.

public override void OnScanResult(ScanCallbackType callbackType, ScanResult result)
{
}

In other words, can I achieve the results from the second method in regards of ScanResult using the first one described?

Take a look at Newtonsoft , it can serialize any object into json string and then deserialize back.

And here we need to convert ScanResult to string first and then pass it into Intent and then deserialize the json to ScanResult in BroadcastReceiver receiver class.

  1. Install the plugin: https://www.nuget.org/packages/Newtonsoft.Json/ .

  2. Convert ScanResult to Json string.

     public override void OnScanResult(ScanCallbackType callbackType, ScanResult result) { string json = JsonConvert.SerializeObject(result); Intent intent = new Intent("MyAction"); intent.PutExtra("MyJson",json); SendBroadcast(intent); }
  3. Convert Json string to ScanResult .

     public override void OnReceive(Context context, Intent intent) { if ("MyAction".Equals(intent.Action)) { string json = intent.GetStringExtra("MyJson"); ScanResult result = JsonConvert.DeserializeObject<ScanResult>(json); // do something } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM