Well, I have everything set up to create a connection to another bluetooth device.
I have a ListView that shows me devices that are paired to my bluetooth device and when I click on the desired device within the listView it should connect to it, but somehow the connection is not being established.
Here is a sample of my paired devices List:
public void getPairedDevices(){
pairedDevices = myBluetoothAdapter.getBondedDevices();
pairedDevices_ArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
if(pairedDevices.size()>0){
for(BluetoothDevice device : pairedDevices){
pairedDevices_ArrayAdapter.add(device.getName()+"\n"+device.getAddress());
}
}
pairedDevices_ListView.setAdapter(pairedDevices_ArrayAdapter);
pairedDevices_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String i = ((TextView) view).getText().toString();
String address = i.substring(i.length() - 17);
deviceToConnectTo = myBluetoothAdapter.getRemoteDevice(address);
connectToDevice(deviceToConnectTo);
}
});
}
And here is my connectToDevice() void:
public void connectToDevice(BluetoothDevice device){
try {
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
myBluetoothAdapter.cancelDiscovery();
} catch (IOException e){}
try{
mmSocket.connect();
} catch (IOException e){
showMsg("Error Connecting to device");
try{
mmSocket.close();
} catch (IOException exception){}
}
}
showMsg is basically a Toast.makeText, it keeps giving me "
Error Connecting to device
toast message, which means that somehow it was impossible to connect.
Can someone tell me why?
I'm using API level 10 and trying to connect to HC-05 Bluetooth Module.
Ok, it seems I managed to fix the problem of not connecting to the HC-05 Bluetooth module. The problem was the UUID I was using.
I changed the UUID to:
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
It's used to bluetooth serial boards such as HC-05.
Related
DiscoveryManager manager = new DiscoveryManager();
manager.setDiscoveryTimeout(10000);
manager.discover(new DiscoveryListener() {
#Override
public void onDiscoveryStarted() {
System.out.println("Discovery started");
}
#Override
public void onDevicesFound(List<Device> devices) {
for (Device device : devices)
System.out.println("Devices found: " + device.getHostName());
}
});
I am using above code for get all host names of IP cameras, One thing I wish to mention before describe my problem. I am using IP webcam android app to make my mobile act like IP cam. With this setup above code give all host names. But this snippet didn't give the actual IP camera's hostname. thank you in advance.
This code is using the Onvif protocol. But IP webcam android app may not be a Onvif device, so this device can not communicate with your the code.
This like:
You are British, I am Vietnamese. You say "What you name?", I don't understand. I need learn English. Like your IP webcam need setup Onvif protocol.
Hello guys here is the solution for this question.
public class OnvifMediaURL {
OnvifManager manager = new OnvifManager();
public void mediaURlFinder(String string) {
OnvifDevice device = new OnvifDevice(string);
manager.getServices(device, new OnvifServicesListener() {
#Override
public void onServicesReceived(#NotNull OnvifDevice onvifDevice, OnvifServices paths) {
}
});
manager.getDeviceInformation(device, new OnvifDeviceInformationListener() {
#Override
public void onDeviceInformationReceived(#NotNull OnvifDevice device,
#NotNull OnvifDeviceInformation deviceInformation) {
// TODO Auto-generated method stub
}
});
manager.getMediaProfiles(device, new OnvifMediaProfilesListener() {
#Override
public void onMediaProfilesReceived(#NotNull OnvifDevice device,
#NotNull List<OnvifMediaProfile> mediaProfiles) {
manager.getMediaStreams(device, mediaProfiles.get(0), new OnvifMediaStreamURIListener() {
#Override
public void onMediaStreamURIReceived(#NotNull OnvifDevice device,
#NotNull OnvifMediaProfile profile, #NotNull String uri) {
// TODO Auto-generated method stub
System.out.println("URL " + uri); //Printing RTSP URL
}
});
}
});
}
}
Pass the hostname, username and password you got from OnvifDiscovery to the mediaURlFinder( ) method, and it will gie you the RTSP link and you can get some other details like manufacturer, serial number etc..
I want mention that in my case I use my mobile phone as IP camera (using IP Webcam application ) and this code gave RTSP link.
I have a Fresh application with basically no code added to it except the following Code.
If I try it in a simulator it goes into update state and says unsupported.
If I try to run in on a 6 generation ipad (with bluetooth turned on) the application crashes as soon as debugging exits UIButton231_TouchUpInside (and never goes into the catch).
Am I missing anything?
CBCentralManager _central;
partial void UIButton231_TouchUpInside(UIButton sender)
{
try
{
BluetoothLEManager();
}
catch (Exception e)
{
Console.Write(e);
}
}
protected void BluetoothLEManager()
{
try
{
_central = new CBCentralManager(DispatchQueue.CurrentQueue);
_central.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) =>
{
Console.WriteLine("DiscoveredPeripheral: " + e.Peripheral.Name);
Console.WriteLine("RSSI: " + e.Peripheral.RSSI);
};
_central.UpdatedState += (object sender, EventArgs e) =>
{
Console.WriteLine("UpdatedState: " + _central.State);
};
_central.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) =>
{
Console.WriteLine("ConnectedPeripheral: " + e.Peripheral.Name);
};
_central.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) =>
{
Console.WriteLine("DisconnectedPeripheral: " + e.Peripheral.Name);
};
}
catch (Exception e)
{
Console.Write(e);
}
}
In the Image below (code is compacted to make the image shorter), debugging reaches line 62 just fine, but attempting to step over or to just let it continue will close the application, and breakpoints in the catch are not reached.
I have tried shared code in local site , and it also crashes and with some error logs :
After checking this line error :
Got a SIGABRT while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application.
Sometimes that may be caused by permission in iOS . You can have a look at this aticle by James : New iOS 10 Privacy Permission Settings .
Starting in iOS 10, nearly all APIs that require requesting authorization and other APIs, such as opening the camera or photo gallery, require a new key value pair to describe their usage in the Info.plist.
However , in info.plist , you can add the permission of Bluetooth easily as follow and will forget another most important permission :
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Add BlueTooth Peripheral Permission</string>
That's not enough for Bluetooth . You also need to add another permission :
<key>NSBluetoothAlwaysUsageDescription</key>
<string>use Bluetooth</string>
From native info.plist , you also will find it .
This permission is fundamental and necessary . Because this will pop up a permission Dialog window in iOS device .
By the way , there is an offical API about using Bluetooth in Xamarin iOS you can have a look .
public class MySimpleCBCentralManagerDelegate : CBCentralManagerDelegate
{
override public void UpdatedState (CBCentralManager mgr)
{
if (mgr.State == CBCentralManagerState.PoweredOn) {
//Passing in null scans for all peripherals. Peripherals can be targeted by using CBUIIDs
CBUUID[] cbuuids = null;
mgr.ScanForPeripherals (cbuuids); //Initiates async calls of DiscoveredPeripheral
//Timeout after 30 seconds
var timer = new Timer (30 * 1000);
timer.Elapsed += (sender, e) => mgr.StopScan();
} else {
//Invalid state -- Bluetooth powered down, unavailable, etc.
System.Console.WriteLine ("Bluetooth is not available");
}
}
public override void DiscoveredPeripheral (CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
{
Console.WriteLine ("Discovered {0}, data {1}, RSSI {2}", peripheral.Name, advertisementData, RSSI);
}
}
public partial class HelloBluetoothCSharpViewController : UIViewController
{
MySimpleCBCentralManagerDelegate myDel;
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
//Important to retain reference, else will be GC'ed
myDel = new MySimpleCBCentralManagerDelegate ();
var myMgr = new CBCentralManager (myDel, DispatchQueue.CurrentQueue);
}
I write an application for Windows Form. I have a problem with pairing a device with PC. Now the program works next way: switch on the divece, start the program, add divece to Bluetooth device, push connect button. I use the next functions:
public BluetoothClient client = new BluetoothClient();
public string selectedItem { get; set; }
public BluetoothDeviceInfo[] AllDevices;
public void GetDevices()
{
AllDevices = client.DiscoverDevicesInRange();
foreach (BluetoothDeviceInfo Device in AllDevices)
{
if(Device.DeviceName.Contains("Kortes"))
onSetDevices(Device.DeviceName); // event to get device name and add it to ComoBox element on form
}
onSetProgress(); // event, that all devices were found, set progress bar and etc.
}
public void GoConnect()
{
foreach (BluetoothDeviceInfo Device in AllDevices)
{
if (Device.DeviceName.Equals(selectedItem)) // item from ComboBox
{
if (!client.Connected)
client = new BluetoothClient();
client.BeginConnect(Device.DeviceAddress, Device.InstalledServices[0], this.BluetoothClientConnectCallback, client);
break;
}
else
{
MessageBox.Show("Choose the device");
}
}
}
private void BluetoothClientConnectCallback(IAsyncResult ar)
{
//Have no problem with this
}
These functions work very well. I can find and connect with needed device. But the problem is that firstly I need to add my device to Bluetooth device in OS and enter PIN code. How can I improve my code to solve this problem?
I don't want to add device. I want to work with it directly. Which methods can I use to enter PIN code programmatically? The program must work the next way: switch on the device, start the program, and push connect button.
You are trying to connect without pairing.Your code is not working because you have to pair before connecting.
replace
client = new BluetoothClient();
client.BeginConnect(Device.DeviceAddress, Device.InstalledServices[0], this.BluetoothClientConnectCallback, client);
by
BluetoothSecurity.PairRequest(Device.DeviceAddress,"123456");
Check out http://mrbikash.com/bluetooth-discovery-pairing-32feet-net/#pairing for a more detailed explanation.
When I run following code on my phone I get black screen saying there was uncaught exception but whole block is wrapped in try/catch block so it is weird, anyway when I proceed with execution code just gets to "Getting device.." so it obviously fails on this line:
LocalDevice local = LocalDevice.getLocalDevice();
Here is whole method:
public void startBT()
{
try
{
f.append("Getting device..");
LocalDevice local = LocalDevice.getLocalDevice();
f.append("Got local device..");
DiscoveryAgent agent = local.getDiscoveryAgent();
f.append("Got local discovery agent..");
connString = agent.selectService(new UUID(
"86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
f.append("Got connection string - >" + connString);
}
catch (Exception ex)
{
Alert message = new Alert("info");
message.setString(ex.getMessage());
Display.getDisplay(this).setCurrent(message);
}
}
Any ideas?
It looks like device I used doesn't support JSR-82 which is J2ME Bluetooth API(this is built into phone, no way of "installing" it) required to use Bluetooth from J2ME Midlets,here is snippet which should check for JSR-82 support:
public static boolean IsBtJsrComaptible() {
try {
Class.forName("javax.bluetooth.LocalDevice");
return true;
} catch (Exception e) {
return false;
}
}
Please note that I got uncaught exception trying to run above snippet, but maybe it would work on some other device.
I develop simple j2me bluetooth client and have problem with bluetooth device search.
Function startInquiry nothing found.
Client : nokia 5220
Server : my pc with bluetooth adapter
All bluetooth devices is on.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.midlet.*;
import javax.bluetooth.*;
import java.util.Vector;
import javax.microedition.lcdui.*;
/**
* #author Администратор
*/
public class Midlet extends MIDlet implements DiscoveryListener
{
private static Vector vecDevices=new Vector();
private static String connectionURL=null;
private LocalDevice localDevice;
private DiscoveryAgent agent;
private RemoteDevice remoteDevice;
private RemoteDevice[] devList;
private Display display;
private Form form;
public void startApp() {
display = Display.getDisplay(this);
form = new Form( "Client" );
try {
localDevice = LocalDevice.getLocalDevice();
} catch( BluetoothStateException e ) {
e.printStackTrace();
}
form.append("Address: "+localDevice.getBluetoothAddress()+"\n\n");
form.append("Name: "+localDevice.getFriendlyName()+"\n\n");
try {
agent = localDevice.getLocalDevice().getDiscoveryAgent();
form.append("Starting device inquiry... \n\n");
boolean si = agent.startInquiry(DiscoveryAgent.GIAC, this);
if ( si ) {
form.append("true");
} else {
form.append("false");
}
} catch( BluetoothStateException e ) {
}
int deviceCount = vecDevices.size();
if(deviceCount <= 0){
form.append("No Devices Found .");
}
else{
//print bluetooth device addresses and names in the format [ No. address (name) ]
form.append("Bluetooth Devices: ");
for (int i = 0; i < deviceCount; i++) {
remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
form.append( remoteDevice.getBluetoothAddress() );
}
}
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
//add the device to the vector
if(!vecDevices.contains(btDevice)){
vecDevices.addElement(btDevice);
}
}
public void inquiryCompleted(int discType)
{
}
//implement this method since services are not being discovered
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
if(servRecord!=null && servRecord.length>0){
connectionURL=servRecord[0].getConnectionURL(0,false);
}
}
//implement this method since services are not being discovered
public void serviceSearchCompleted(int transID, int respCode) {
}
}
Not sure what the exact problem is, but you definitely don't want to be doing this in your midlet's startApp() method. This is a system lifecycle method, and should return quickly, but scanning for bluetooth devices will block it for a long time. Your startApp() method is tying up the device's resources which it could need for doing the actual scanning!
Refactor, so your device scanning is done in a new thread, then see what happens.
You seem to have misunderstood how the Bluetooth API works. The startInquiry method only starts the device discovery process and returns immediately afterwards, leaving the discovery running in the background. When devices are discovered, you get a callback of the deviceDiscovered method for each of them, and when the discovery process has completed, you get a callback of the inquiryCompleted method. So you need to move the accessing of the vecDevices member and the form manipulation from startApp to inquiryCompleted to be able to actually show the discovered information.
You say all devices are on - but also check if all devices are discoverable.
I've made this mistake before myself!
Lookup the method LocalDevice.setDiscoverable() if you want to toggle between modes programatically.