Android Studio - searching bluetooth devices - android

I would like to write an app that can search bluetooth devices, add founded devices to ListView, connect with one of this devices and send some text. But now I am not able to search devices. When I was overlooking logs I noticed that sometimes the searching works. But even if it worked nothing was added to the ListView.
It can be important - I have devices with Android 4.2 and 5.1.
Could anybody help me find mistakes in my code?
This is my code:
public class MainActivity extends Activity {
Button btnSearch;
Button btnConnect;
Button btnSend;
ListView lvDeviceList;
TextView tvOutgoingMessage;
TextView tvIncomingMessage;
BluetoothAdapter bluetoothAdapter;
BroadcastReceiver broadcastReceiver;
public ArrayList<String> BTDevices = new ArrayList<>();
public ListAdapter deviceListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "ONCREATE");
btnSearch = (Button) findViewById(R.id.btnSearch);
btnConnect = (Button) findViewById(R.id.btnConnect);
btnSend = (Button) findViewById(R.id.btnSend);
lvDeviceList = (ListView) findViewById(R.id.devicesList);
tvOutgoingMessage = (TextView) findViewById(R.id.outgoingMessage);
tvIncomingMessage = (TextView) findViewById(R.id.incommingMessage);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (checkIfEnable()) {
Log.d(TAG, "ONCREATE - IF");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
discoverDevices();
connect();
}
}
});
}
public boolean checkIfEnable() {
boolean existance = true;
Log.d(TAG, "CHECK IF ENABLE");
if (bluetoothAdapter == null) {
Log.d(TAG, "IN 1ST IF");
Toast.makeText(getApplicationContext(), "Your device doesn't support Bluetooth", Toast.LENGTH_LONG).show();
existance = false;
}
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
Log.d(TAG, "IN 2ND IF");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
return existance;
}
private void discoverDevices() {
Log.d(TAG, "DISCOVER DEVICES");
bluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);
// Create a BroadcastReceiver for ACTION_FOUND.
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "ON RECEIVE");
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
BTDevices.add(deviceName);
lvDeviceList.setAdapter(deviceListAdapter);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
}
}
};
}
private void connect() {
Log.d(TAG, "CONNECT");
}
Thanks in advance.

First of all, you shouldn't call lvDeviceList.setAdapter(deviceListAdapter) on each device found. Move this line to onCreate(). The second - you should pass BTDevices to your adapter(this part is important and it's missing in your code) and on each BTDevices.add(deviceName) you should call notifyDataSetChanged() on your adapter.

Related

My bluetooth app is not working properly and work only after opening my bluetooth setting activity

I am developing an app which can discover all local bluetooth supported devices if bluetooth is on. But I am in a problem and which is as follow:
When I am running my app and wait for available devices it does not show any device which is on , but when I navigate to bluetooth setting activity(in-built phone activity)
then it shows all local available devices there as well as in my app when I returned back. Please help me. I want to discover all devices by staying on my app and want to see a list of those devices.
I have took permission of BLUETOOTH,BLUETOOTH ADMIN,ACCESS_FINE_LOCATION.
Here is my main activity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "bluetooth";
private BluetoothAdapter bluetoothAdapter;
private Button mBTEnableButton;
private BroadcastReceiver mReceiver;
private TextView mShowDevices;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBTEnableButton = findViewById(R.id.enable_bt_button);
mShowDevices = findViewById(R.id.show_connected_devices);
mProgressBar = findViewById(R.id.progressbar);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mReceiver = new BlueToothReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, intentFilter);
mProgressBar.setVisibility(View.INVISIBLE);
if (bluetoothAdapter == null) {
Toast.makeText(this, "Device does not support bluetooth", Toast.LENGTH_SHORT).show();
}
mBTEnableButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!bluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
bluetoothAdapter.startDiscovery();
}
}
});
}
private class BlueToothReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("bluetooth", "onReceive");
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceAddress = device.getAddress();
mShowDevices.setText("action : " + action + "\n device name: " + deviceName + "\ndevice address : " + deviceAddress);
Log.d("bluetooth", "action : " + action + "\n device name: " + deviceName + "\ndevice address : " + deviceAddress);
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mProgressBar.setVisibility(View.VISIBLE);
Log.d(TAG, "discovery start: ");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressBar.setVisibility(View.INVISIBLE);
Log.d(TAG, "discovery finish: ");
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}}

How to discover Bluetooth devices Programatically in android and display in Listview

I tried and followed some tutorial on web but it didn't work on new Android versions.
I declared all Bluetooth permissions and used Dexter permission library. I followed few answers but it doesn't display available Bluetooth device name also
Below is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toast("starts scanning...");
mBluetoothAdapter.startDiscovery();
}
});
mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String bluetoothDevice = mAdapter.getItem(i);
toast(bluetoothDevice);
}
});
}
public void pairedDevicesListView(View view){
mAdapter.clear();
pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices){
mAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
}
To discover a device, first get the bluetooth adapter by calling BluetoothAdapter.getDefaultAdapter()
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
To start discover, simply call the startDiscovery() from bluetooth adapter. This process is asynchronous so it will return immediately. To catch the discovery process, we can register a BroadcastReceiver with ACTION_FOUND, ACTION_DISCOVERY_STARTED, ACTION_DISCOVERY_STARTED. For each device found, the intent will carry extra field EXTRA_DEVICE containg the BluetoothDevice object.
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
adapter.startDiscovery();
The receiver:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
showToast("Found device " + device.getName());
}
}
};
And, don’t forget to unregister the receiver on Activity’s onDestroy method:
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
Add manifest permissions as follows
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />`
and try following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnstart=findViewById(R.id.btnstart);
mListView=findViewById(R.id.listofdevices);
final ArrayAdapter mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
mListView.setAdapter(mAdapter);
txt1=findViewById(R.id.txt1);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
setdevicevisible();
boolean hasBluetooth = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
if(!hasBluetooth) {
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
dialog.setTitle(getString(R.string.bluetooth_not_available_title));
dialog.setMessage(getString(R.string.bluetooth_not_available_message));
dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Closes the dialog and terminates the activity.
dialog.dismiss();
MainActivity.this.finish();
}
});
dialog.setCancelable(false);
dialog.show();
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
}
// If another discovery is in progress, cancels it before starting the new one.
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
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
mAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
I forgot to declare Location permissions in the manifest file. To discover Bluetooth devices programmatically you need to add two permission i.e. ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION.
You could use the MAC address as unique ID.
And you can find in the official doc here a complete example of it
https://developer.android.com/guide/topics/connectivity/bluetooth.html#FindingDevices
About signal strength i think you should use RSSI (Received Signal Strength Indicator)
Edit: An easy way to accomplish this will be like this snippet to find bluetooth devices
mBluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
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());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
hope it helps
happy coding
Try using this code, it worked for me.
public class DeviceListActivity extends Activity {
private ListView pairedDevicesListView, newDevicesListView;
private ArrayList<DeviceData> dataList= new ArrayList<DeviceData>();
private ArrayList<BluetoothDevice> pairedDevices=new ArrayList<BluetoothDevice>();
private BluetoothAdapter bluetoothAdapter;
BluetoothDevice device;
private ArrayAdapter newDeviceAdapter;
private DeviceListAdapter pairedDeviceAdapter;
public static String DEVICE_ADDRESS = "device_address";
private IntentFilter filter;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("action", action);
// Toast.makeText(DeviceListActivity.this, action, Toast.LENGTH_SHORT).show();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
newDeviceAdapter.add(device.getName() + "\n" + device.getAddress());
pairedDevices.add(device);
newDeviceAdapter.notifyDataSetChanged();
}
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
if (newDeviceAdapter.getCount() == 0) {
Toast.makeText(DeviceListActivity.this, "No devices found", Toast.LENGTH_SHORT).show();
newDeviceAdapter.add("No new device found");
newDeviceAdapter.notifyDataSetChanged();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_device_list);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevicesListView = (ListView) findViewById(R.id.avail_devices);
newDevicesListView=(ListView)findViewById(R.id.new_devices);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDeviceAdapter = new DeviceListAdapter(this,dataList, pairedDevices);
pairedDevicesListView.setAdapter(pairedDeviceAdapter);
pairedDeviceAdapter.notifyDataSetChanged();
//-----------------------------------------------
newDeviceAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
newDevicesListView.setAdapter(newDeviceAdapter);
newDeviceAdapter.notifyDataSetChanged();
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
// get paired devices
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
// pairedDeviceAdapter.clear();
for(BluetoothDevice device : pairedDevice)
{
// pairedDeviceAdapter.add(device.getName()+ "\n" +device.getAddress());
dataList.add(new DeviceData(device.getName(),device.getAddress()));
pairedDevices.add(device);
}
pairedDeviceAdapter.notifyDataSetChanged();
}
// register broadcast receiver
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);
pairedDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String data = ((TextView) view).getText().toString();
String address = data.substring(data.length() - 17);
Intent intent = new Intent();
intent.putExtra("device_address", address);
intent.putExtra("info", data);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
newDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
Boolean isBonded = false;
try {
isBonded = createBond(device);
if(isBonded)
{
Log.i("Log","Paired");
// pairedDeviceAdapter.add(device.getName() + "\n" + device.getAddress());
dataList.add(new DeviceData(device.getName(),device.getAddress()));
newDeviceAdapter.remove(device.getName() + "\n" + device.getAddress());
pairedDeviceAdapter.notifyDataSetChanged();
newDeviceAdapter.notifyDataSetChanged();
// Toast.makeText(DeviceListActivity.this, "paired to:" +device.getName(), Toast.LENGTH_SHORT).show();
// ------------------------
// Intent intent = new Intent();
// intent.putExtra("device_address", device.getAddress());
// intent.putExtra("info", device.getName());
// setResult(Activity.RESULT_OK, intent);
// finish();
}
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(broadcastReceiver, filter);
}
#Override
protected void onPostResume() {
super.onPostResume();
registerReceiver(broadcastReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (bluetoothAdapter != null) {
bluetoothAdapter.cancelDiscovery();
}
this.unregisterReceiver(broadcastReceiver);
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
}

Bluetooth Connection gets lost in Android

I am able to connect Bluetooth printer with my application when I open an activity but as soon as I navigate to another activity/screen and again come back to that screen, the connection is lost. What I want is that I need to connect to a Bluetooth device only once until I disable Bluetooth from my phone.
Here's the code:
public class Activity_Payment extends ActionBarActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
mActivity = Activity_Payment.this;
// To start bluetooth for printing receipts.....
mService = new BluetoothService(this, mHandler);
//À¶ÑÀ²»¿ÉÓÃÍ˳ö³ÌÐò
if( mService.isAvailable() == false ){
Toast.makeText(this, "Bluetooth is not available",
Toast.LENGTH_LONG).show();
finish();
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
if( mService.isBTopen() == false)
{
Intent enableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) { //ÇëÇó´ò¿ªÀ¶ÑÀ
System.out.println("====inresltttt11");
if (resultCode == Activity.RESULT_OK) { //À¶ÑÀÒѾ­´ò¿ª
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
Intent serverIntent = new Intent(Activity_Payment.this,DeviceListActivity.class); //ÔËÐÐÁíÍâÒ»¸öÀàµÄ»î¶¯
startActivityForResult(serverIntent,REQUEST_CONNECT_DEVICE);
} else { //Óû§²»ÔÊÐí´ò¿ªÀ¶ÑÀ
finish();
}
}
else if (requestCode == REQUEST_CONNECT_DEVICE){
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
Toast.makeText(this, "Bluetooth connected",
Toast.LENGTH_LONG).show();
}
}
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED: //ÒÑÁ¬½Ó
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
deviceConnected = true;
break;
case BluetoothService.STATE_CONNECTING: //ÕýÔÚÁ¬½Ó
Log.d("À¶ÑÀµ÷ÊÔ","ÕýÔÚÁ¬½Ó.....");
break;
case BluetoothService.STATE_LISTEN: //¼àÌýÁ¬½ÓµÄµ½À´
case BluetoothService.STATE_NONE:
Log.d("À¶ÑÀµ÷ÊÔ","µÈ´ýÁ¬½Ó.....");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST: //À¶ÑÀÒѶϿªÁ¬½Ó
Toast.makeText(getApplicationContext(), "Device connection was lost,
Please try again.",
Toast.LENGTH_SHORT).show();
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT: //ÎÞ·¨Á¬½ÓÉ豸
Toast.makeText(getApplicationContext(), "Unable to connect device,
Please try again.",
Toast.LENGTH_SHORT).show();
serverIntent = new
Intent(Activity_Payment.this,DeviceListActivity.class);
startActivityForResult(serverIntent,REQUEST_CONNECT_DEVICE);
break;
}
}
};
}
public class DeviceListActivity extends Activity {
// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
public static String EXTRA_DEVICE_UUID = "device_uuid";
// Member fields
BluetoothService mService = null;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list); //ÏÔʾÁбí½çÃæ
// Set result CANCELED incase the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
Button cancelButton = (Button) findViewById(R.id.button_cancel);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
// v.setVisibility(View.GONE);
}
});
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
// Set result and finish this Activity
setResult(Activity.RESULT_CANCELED, intent);
finish();
}
});
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
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);
mService = new BluetoothService(this, null);
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mService.getPairedDev();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null) {
mService.cancelDiscovery();
}
mService = null;
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mService.isDiscovering()) {
mService.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mService.startDiscovery();
}
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() { //µã»÷ÁбíÏÁ¬½ÓÉ豸
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mService.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
Log.d("Á¬½ÓµØÖ·", address);
System.out.println("=====address: "+address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#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) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices =
getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
I recommend moving all of your bluetooth connection-management code into a Service. Use a BroadCastReceiver to catch events such as when bluetooth is turned on or off, and then your receiver can invoke the service by sending the information in an Intent. A service can run in the background even when the activity is not active.

Android Bluetooth listing and pairing request send

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;
/** 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 {
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
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();
}
}
}
}
}
}
}
};
}
As Bluetooth is working on Serial Ports and to communicate between two device using serial port you need to UUID (Universally Unique Identifier)
as you had not mentioned any UUID so you can not communicate from bluetooth.
According to your requirement there is a simple and best example for Bluetooth Chat with secure and non-Secure devices available in Android-SDK
Bluetooth-Chat Source Code

How to discover the Bluetooth device in Android?

I am developing an application where I have to connect to Bluetooth device.
I use "adb push" to push my apk to android x86.
The bluetooth of Android-x86 is normal,and it can scan the bluetooth device.
I use two button here.
One of the button call "scan", it list the device that I have paired.
another one call discover,it work is scan the bluetooth device.
Now I can use the "scan button" to list the device that I have paired.
But when I want to use the "discover" button to scan the device by my app, it always crash when I type the code into btn_discover.setOnClickListener:
what should I do?
Here is my code.
public class Main extends Activity {
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_SELECT_DEVICE = 1;
private Button btn_scan;
private Button btn_discover;
private TextView pair_list;
private TextView scan_list;
private Set<BluetoothDevice> pairedDevices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_scan = (Button)findViewById(R.id.btn_scan);
pair_list = (TextView)findViewById(R.id.pair_list);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null)
{
Toast.makeText(this, "No support bluetooth", Toast.LENGTH_SHORT).show();
return;
}else if(mBluetoothAdapter != null) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_SELECT_DEVICE);
}
//******************scan按鈕動作-將已配對過的藍芽裝置列出來
btn_scan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size()>0) {
for(BluetoothDevice bDevice : pairedDevices) {
pair_list.append(bDevice.getName() + "\n" + bDevice.getAddress() + "\n" + bDevice.getBondState() + "\n" );
}
}
}
});
//******************scan按鈕動作結束
btn_discover.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
});
}
protected void onDestroy() {
super.onDestroy();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
scan_list.append(device.getName() + "\n" + device.getAddress() + "\n");
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
`
I solve it.
I add a new xml file name device_name .
And modify the code of the following:
newDevicelistArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
And It can show the bluetooth device by ListView.

Categories

Resources