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.
Related
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.
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();
}
}
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
Hi everyone..
I have used android Bluetooth chat application code in my application
I want pass a device name to another activity so i have saved my device name in public static variable when i select device name from list view same as android chat application.
After that i used this device name in another activity .With the help of this device name i Started BluetoothChatservice in second activity same as bluetooth chat standard code example.I didnt used this services in my mainactivity because I want connect device in my second activity
I have used Secure key only.But when i satarted this service sometimes connection connected with my another devices or sometimes not .
When i try for connection from both side connection connected.But first time it is not connect .I have used many things for service start like in onResume or ONStart or OnCreate but i am not success ed. MY english not good so please read carefully.
MY Main Activity Code=======
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private TextView mTitle;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private Button mSearch;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
public static BluetoothAdapter mBluetoothAdapter = null;
private LinearLayout mLin_getView;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
// Set up the custom title
mLin_getView=(LinearLayout) findViewById(R.id.mLin_addView);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#SuppressLint("NewApi")
#Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
//if (mChatService == null)
setupChat();
}
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
}
#SuppressLint("NewApi")
private void setupChat() {
Log.d(TAG, "setupChat()");
mSearch = (Button) findViewById(R.id.btn_search);
mSearch.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
initilizeFiled();
/*Intent serverIntent = new Intent(BluetoothChat.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);*/
}
});
mOutStringBuffer = new StringBuffer("");
}
protected void initilizeFiled() {
// TODO Auto-generated method stub
Button scanButton = (Button) findViewById(R.id.button_scan);
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);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// 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);
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#SuppressLint("NewApi")
#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);
}
}
}
};
// 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
mBtAdapter.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);
Log.d("Device Address", address);
connectDevice(address, true);
}
};
#SuppressLint("NewApi")
private void doDiscovery() {
if (D) Log.d(TAG, "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 (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
//if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
// The Handler that gets information back from the BluetoothChatService
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(String Address,boolean secure) {
// Get the device MAC address
String address = Address;
// Get the BLuetoothDevice object
// BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Const.deviceName=device;
Intent ib=new Intent(DashboardActivity.this,RemmoteActivity.class);
startActivity(ib);
}
}
Second Activity=========
private BluetoothAdapter mBluetoothAdapter = null;
private String mConnectedDeviceName = null;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
String TAG="Remmote";
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
ImageView Img_video, Img_camera, Img_song, Img_play, Img_forward,
Img_backward, Img_volume_up, Img_volume_down, Img_splash,
Img_capture, Img_zoom_in, Img_zoom_out;
private BluetoothChatService mChatService=null;
private StringBuffer mOutStringBuffer;
private BluetoothDevice device_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote_screen);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mChatService=new BluetoothChatService(this,mHandler);
mOutStringBuffer=new StringBuffer("");
mOutStringBuffer=new StringBuffer("");
device_Name=Const.device;
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
initilizeField();
}
public void onStart() {
super.onStart();
Log.print(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "Bluetooth Device Enabled", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth Device Enabled", Toast.LENGTH_SHORT).show();
}
}
#Override
public synchronized void onResume() {
super.onResume();
Log.print(TAG, "+ ON RESUME +");
mChatService.connect(device_Name, true);
}
#Override
public synchronized void onPause() {
super.onPause();
Log.print(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
Log.print(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null) mChatService.stop();
Log.print(TAG, "--- ON DESTROY ---");
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.mImg_camera:
sendMessage("Camera");
break;
case R.id.mImg_video:
break;
case R.id.mImg_songs:
break;
case R.id.Img_play:
break;
case R.id.Img_forward:
break;
case R.id.Img_backward:
break;
case R.id.Img_volume_up:
break;
default:
break;
}
}
public void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
// mOutEditText.setText(mOutStringBuffer);77
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Const.Camera:
com.example.utils.Log.print("your tab is here====="+1000);
//BluetoothChat.this.sendMessage("Camera");
break;
case MESSAGE_STATE_CHANGE:
Log.print(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "STATE_CONNECTED", Toast.LENGTH_SHORT).show();
break;
case BluetoothChatService.STATE_CONNECTING:
Toast.makeText(getApplicationContext(), "STATE_CONNECTING", Toast.LENGTH_SHORT).show();
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
Toast.makeText(getApplicationContext(), "STATE_NOT_LISTEN", Toast.LENGTH_SHORT).show();
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
Toast.makeText(getApplicationContext(), writeMessage, Toast.LENGTH_SHORT).show();
//mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Toast.makeText(getApplicationContext(), "Read", Toast.LENGTH_SHORT).show();
// captureImage();
// mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
In const Class for public static varible
public static BluetoothDevice device;
BluetoothChatService Code Same as android default program example
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.