I have a very simple activity for discovering other android devices via bluetooth:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Get the local Bluetooth adapter
FrameLayout f = new FrameLayout(this);
setContentView(f);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// Request discover from BluetoothAdapter
Log.i("bluetooth", "about to start device discovery");
mBtAdapter.startDiscovery();
//start receiving stuff
mReceiver = new BluetoothReceiver();
}
The problem is that the BluetoothRecieiver class called at the end of the activity's onCreate() doesn't seem to find and devices, although I have one turned on in the vicinity when I am debugging this:
public class BluetoothReceiver extends BroadcastReceiver {
public ArrayAdapter<String> mNewDevicesArrayAdapter;
#Override
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);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
Log.i("face", device.getName() + "\n" + device.getAddress());
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (mNewDevicesArrayAdapter.getCount() == 0) {
Log.i("face", "found NOTHING!");
mNewDevicesArrayAdapter.add("no devices found");
}
}
}
}
Is there anything I am missing here?
I think it's because when you call registerReceiver() mReceiver is null, move mReceiver = new BluetoothReceiver(); above the first this.registerReceiver(mReceiver, filter);, also you could do something like
filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
and then call this.registerReceiver(mReceiver, filter); only one time
Related
I'm trying to make an android app which has some issues about Bluetooth. I simply enable Bluetooth, find devices, connect one of the devices, send & receive data. First thing is done. But in second, there are some problems. I make a Broadcast Receiver to discover devices nearby my phone. But OnReceive method doesn't get called. The weird thing is, it was getting called at first and I was able to see devices nearby. Then something that I cannot figure out happened and now OnReceive method doesn't get called. I've searched topics about these but none of them could solve my problem. MyDevice and MyAdapter are my own classes to show Bluetooth devices in listview with my own layout. Here is my code:
public class FoundDevicesActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
ListView foundedDevicesListView;
MyDeviceAdapter deviceAdapter;
List<MyDevice> foundedDevicesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_found_devices);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
foundedDevicesListView = (ListView) findViewById(R.id.foundDevicesListview);
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(receiver, filter);
bluetoothAdapter.startDiscovery();
deviceAdapter = new MyDeviceAdapter(this, foundedDevicesList);
foundedDevicesListView.setAdapter(deviceAdapter);
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(FoundDevicesActivity.this, "Discovery is started !!", Toast.LENGTH_SHORT).show();
Log.d("Found Devices Activity", "Discovery is started !!");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
MyDevice dvc = new MyDevice();
if (device.getName().equals(null)) {
dvc.name = "UNDEFINED NAME";
} else {
dvc.name = device.getName();
}
if(device.getAddress().equals(null)) {
dvc.address = "UNDEFINED ADDRESS";
} else {
dvc.address = device.getAddress();
}
foundedDevicesList.add(dvc);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
bluetoothAdapter.cancelDiscovery();
Toast.makeText(FoundDevicesActivity.this, "Discovery is finished !!", Toast.LENGTH_SHORT).show();
Log.d("Found Devices Activity", "Discovery is finished !!");
}
}
};
}
Any idea ?
That I use android app to get the hardware's ble name ,but i can get the name that using iOS .I can't find any error of this. so what i should do for this issue.
here, i copy my code for looking .
First:
BluetoothManager bluetoothManager = (BluetoothManager)
getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
bluetoothAdapter.startDiscovery();
Next:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mReceiver,filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
getActivity().registerReceiver(mReceiver,filter);
last:
public BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("走进receiver","bluetooth");
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
String sname = device.getName();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
}
}
};
I want the device which user selects in list paired. in program search in bluetooth device and show list of bluetooth device to user.
if(ba.isEnabled()){
if (ba.isDiscovering()) {
ba.cancelDiscovery();
}
ba.startDiscovery();
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
arr.add(device.getName() + "\n" + device.getAddress());
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
}
Go in your sdk>sample>android-7>BluetoothChat .import BluetoothChat demo app in your eclipse.It will be helpfull for you
I need some help in my Android application. I am trying to create an app that discovers bluetooth devices then compare the name to a string.
but I encountered 2 problems.
1: when I exit the app (back button) it exits then show me a crash message (after few seconds) .. I think the problem is with "mReceiver" (check "2nd problem).
2:(main problem) In the code bellow, the $"mReceiver = new BroadcastReceiver()" part has a problem. I have thrown multiple toasts every where just to check which part doesn't work, everything before this line works fine.
I'm not sure but I think the problem with not having "final" in declaring "mReciver" in the beginning --> "private BroadcastReceiver mReceiver;". However adding final causes problems.
The Code:
public class MainActivity extends Activity {
private final static int REQUEST_ENABLE_BT = 1; //It's really just a number that you provide for onActivityResult (>0)
//Temp objects for testing
private String StringMeeting = "meeting";
ProgressBar bar;
//Member fields
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
// Create a BroadcastReceiver for ACTION_FOUND
private BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare & start progress bar
bar = (ProgressBar) findViewById(R.id.progressBar1);
bar.setVisibility(View.VISIBLE);
//------------Setup a Bluetooth (Get Adapter) ------------------
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(getApplicationContext(), "This Device does not support Bluetooth", Toast.LENGTH_LONG).show();
}else{Toast.makeText(getApplicationContext(), "Getting the Adabter is done", Toast.LENGTH_SHORT).show();}
//------------Setup a Bluetooth (Enable Bluetooth) ------------------
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}else{Toast.makeText(getApplicationContext(), "Enable Bluetooth is done", Toast.LENGTH_SHORT).show();}
//------------Finding Devices (Discovering Devices)----------------------
// Create a BroadcastReceiver for ACTION_FOUND
Toast.makeText(getApplicationContext(), "creating the mReceiver", Toast.LENGTH_SHORT).show(); //last thing works
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "accessed onReceive + will create action", Toast.LENGTH_SHORT).show();
String action = intent.getAction();
Toast.makeText(getApplicationContext(), "Waiting to discover a device", Toast.LENGTH_SHORT).show();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Toast.makeText(getApplicationContext(), "enterd the if", Toast.LENGTH_SHORT).show();
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(getApplicationContext(), "Getting device names", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), device.getName(), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "displaying the name should be done", Toast.LENGTH_SHORT).show();
// Add the name and address to an array adapter to show in a ListView
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}else{Toast.makeText(getApplicationContext(), "Error: BluetoothDevice.ACTION_FOUND.equals(action) = False", Toast.LENGTH_SHORT).show();}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
} //onCreate end
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
}
Thank You For Your Time.
You start an activity for result in order for the user to be prompted whether the user allows Bluetooth to be enabled or not, but you don't wait for the result and try to find devices right away.
You should implement onActivityResult call back. If the result is RESULT_OK, then you start discovering devices. Enabling bluetooth takes some time.
I'm using code from the Android developer website to detect Bluetooth devices in range, and adding them to an ArrayAdapter. Problem is, each device gets added to the ArrayAdapter 5-6 times. Right now, I'm just using the code from here: http://developer.android.com/guide/topics/connectivity/bluetooth.html#DiscoveringDevices
Here's what I have:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
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
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
Any idea what's causing this? And what can I do to get a device to be added only once to the ArrayAdapter, instead of 5 times?
I'm not sure if its a bug or what but I've also experienced this on some of my devices. To solve this, add found devices in a List only once with some checks. See below:
private List<BluetoothDevice> tmpBtChecker = new ArrayList<BluetoothDevice>();
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery starts
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
//clearing any existing list data
tmpBtChecker.clear();
}
// 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
if(!tmpBtChecker.contains(device)){
tmpBtChecker.add(device);
mArrayAdapter.add(device.getName()+"\n"+device.getAddress());
}
}
}
};