I'm doing an app which uses bluetooth communication.
At first, I'm trying to get a list of all bluetooth devices detectable by the device.
I've managed to load in a listview all the paired devices, but i'm unable to list un-paired devices, I've found some tutorials but I'm a bit confused as I'm a bit new to android development & bluetooth communication.
So i need to find every bluetooth device in range, and I don't know how to do it (lazy)
Here is the (edited) code:
package com.voice.benz.instaurentremote;
import android.bluetooth.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.widget.ArrayAdapter;
import java.util.Set;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.view.Window;
import android.app.Activity;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
public class bluetooth extends ActionBarActivity {
private TextView bluetoothPaired;
private TextView txt_status;
private BluetoothAdapter btAdapter;
private ListView newdevices_listview;
private Set<BluetoothDevice>pairedDevices;
private ArrayAdapter<String> adapter = null;
private static final int BLUETOOTH_ON = 1000;
private static final int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
// Initialize the button to perform device discovery
txt_status = (TextView) findViewById(R.id.txt_status);
newdevices_listview = (ListView)findViewById(R.id.newdevices_listview);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
newdevices_listview.setAdapter(adapter);
// Initialize adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
}
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);
txt_status.setText("Found device " + device.getName());
adapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
public void attivaBluetooth (View view) {
if (!btAdapter.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 1);
}
}
public void cercaDispositivi (View view)
{
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
btAdapter.startDiscovery();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(mReceiver);
}
public void disattivaBluetooth (View view)
{
if (btAdapter.isEnabled())
{
btAdapter.disable();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bluetooth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You don't seem to be registering your BroadcastReceiver myBluetoothReceiver anywhere. If you do that in onResume() or onCreate you'll probably have more luck. :)
Related
I'm starting to develop an app to communicate with an arduino device through bluetooth.
I'm initializing the bt adapter with
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
The problem is that btAdapter returns null,
txt_status.append("\nAdapter " + btAdapter);
Its like the device hasn't got a bluetooth adapter, which is not my case.
Any ideas? I'm searching around with no luck.
Thanks, Federico
Complete code of the activity:
package com.voice.benz.instaurentremote;
import android.bluetooth.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.bluetooth.BluetoothAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.content.Intent;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import java.util.Set;
import android.content.Context;
import android.util.Log;
public class bluetooth extends ActionBarActivity {
private TextView bluetoothPaired;
private TextView txt_status;
private BluetoothAdapter btAdapter;
private ListView listview_devices;
private Set<BluetoothDevice> dispositivi;
private ArrayAdapter<String> adapter = null;
private static final int BLUETOOTH_ON=1000;
private TextView txt_bluetoothStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
txt_bluetoothStatus = (TextView) findViewById(R.id.txt_bluetooth_status);
txt_status = (TextView) findViewById(R.id.txt_status);
listview_devices = (ListView) findViewById(R.id.listView_devices);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
listview_devices.setAdapter(adapter);
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null)
{
System.out.println ("Bluetooth non supportato");
}
else
{
System.out.println ("Bluetooth inizializzato");
}
if (btAdapter.isEnabled())
{
// Il bluetooth è già attivato
String mydeviceaddress = btAdapter.getAddress();
String mydevicename = btAdapter.getName();
String status = mydevicename + " : " + mydeviceaddress;
txt_bluetoothStatus.setText(status);
}
else
{
// Attiva bluetooth
}
}
public void attivaBluetooth (View view) {
if (btAdapter != null && !btAdapter.isEnabled())
{
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, BLUETOOTH_ON);
}
//else
//load();
}
public void disattivaBluetooth (View view)
{
if (btAdapter.isEnabled())
{
btAdapter.disable();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==BLUETOOTH_ON && resultCode==RESULT_OK)
{
load();
}
}
private void load()
{
dispositivi = btAdapter.getBondedDevices();
adapter.clear();
for(BluetoothDevice bt : dispositivi)
adapter.add(bt.getName());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bluetooth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Replace your code line,
#Override
protected void onCreate(Bundle savedInstanceState) {
...
...
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
with
btAdapter = BluetoothAdapter.getDefaultAdapter();
its all about local variable and Class level variable.
You are getting Bluetooth adapter in onCreate as local variable and accessing outside of onCreate() the class level variable which is not initialized and always remain null.
I develop an bluetooth app which will connect to a paired device and send a message, but I have to test connection before. I've tried many options, but nothing works in good way. So could you send me any example of code which can do it? I made an thread, but I can't get an good state of connection to build an "if" function. Here is the code:
package com.example.szukacz;
import java.lang.reflect.Method;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
LinearLayout sparowaneUrzadzenia;
public void lokalizowanie() {
Intent intencja = new Intent(this, Lokalizator.class);
startActivity(intencja);
}
public void parowanie(View v) {
Intent intencja = new Intent(this, Parowanie.class);
startActivity(intencja);
}
boolean isRunning;
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String status = (String)msg.obj;
if(status == "polaczony") {
alarm();
showToast("prawda, zwraca" + status);
} else {
showToast("wykonanie x, zwraca: " + status);
};
}
};
public void alarm() {
showToast("Alarm!!!");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sparowaneUrzadzenia = (LinearLayout) findViewById(R.id.listaUrzadzenGlowna);
pokazSparowane();
}
public void onStop() {
super.onStop();
isRunning = false;
}
public void onStart() {
super.onStart();
Thread testPolaczen = new Thread(new Runnable() {
public void run() {
try {
for(int i = 0; i < 1000000; i++) {
Thread.sleep(5000);
testujPolaczenia();
int stan = 0;
String status = Integer.toString(stan);
Message msg = handler.obtainMessage(1, (String)status);
if(isRunning == true) {
handler.sendMessage(msg);
}
}
} catch (Throwable t) {
// watek stop
}
}
});
isRunning = true;
testPolaczen.start();
}
private void testujPolaczenia() {
}
public void pokazSparowane(){
/*
* Wyświetlanie listy sparowanych urządzeń .
* */
Log.d("INFO","Sparowane dla tego urzÄ…dzenia");
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
Log.d("INFO",device.getName()+" - "+device.getAddress());
// dodawanie urzadzen do listy
Button urzadzenie = new Button(getApplicationContext());
urzadzenie.setText(device.getName());
// urzadzenie.setTextColor(0xffffff); //jak ustawic na czarny kolor napsisów ?
urzadzenie.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
showToast("klik");
lokalizowanie();
}
});
sparowaneUrzadzenia.addView(urzadzenie);
}
} else {
showToast("brak sparowanych urzadzen");
}
}
#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;
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
thanks!
I faced the same problem as I am working on an app which may use TTS while it is running. I think there is no way to check if there is any bluetooth device connected by the BluetoothAdapter class immediately except creating a broadcast receiver and monitor the changes of status of bluetooth.
After scratching my head for a few hours, I found a quite subtle way to solve this problem. I tried, it works pretty well for me.
AudioManager audioManager = (AudioManager) getApplicationContext.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.isBluetoothA2dpOn()) {
//audio is currently being routed to bluetooth -> bluetooth is connected
}
Source: http://developer.android.com/training/managing-audio/audio-output.html
I think it's to late for answer to your question but I think can helps somebody :
If you use Thread you have to create a BroadcastReceiver in your main activity on create :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_digital_metrix_connexion);
BroadcastReceiver bState = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED))
{
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state)
{
case BluetoothAdapter.ACTION_ACL_CONNECTED:
{
//Do something you need here
System.out.println("Connected");
break;
}
default:
System.out.println("Default");
break;
}
}
}
};
}
BluetoothAdapter.STATE_CONNECTED is one state over many, for exemple it's possible to check if device connecting or disconnecting thanks to BluetoothAdapter.ACTION_ACL_DISCONNECTED or BluetoothAdapter.ACTION_ACL_DISCONNECTED_REQUEST .
After, you have to create a filter in your thread class or in you main activity if you don't use thread :
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
This filter check the bluetoothadapter state.
And now you have to register your filter so if you use thread pass context in parameter of your thread like this context.registerReceiver(bState,filter);
or in your main Activity : registerReceiver(bState,filter);
If you have any question don't hesitate to ask me.
Hope I helps you somebody.
I am having some difficulty passing the right information to set up Bluetooth discovery and pairing. I have been following the Android developer example documents pretty closely and have not been able to figure out what I need to pass to this method. This is the site I have been using, for reference.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
TransferFragment:
//some code used from
// http://examples.javacodegeeks.com/android/core/ui/progressdialog/android-progressdialog-example/
// http://developer.android.com/guide/topics/connectivity/bluetooth.html
package com.project.BluetoothTransfer_v1000;
import java.util.Set;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class TransferFragment extends Fragment{
private TextView filePathTextView;
private Button startTransferButton;
private ImageView bluetoothImage;
ProgressDialog transferDialog;
Handler updateBarHandler;
private static final int REQUEST_BLUETOOTH = 1;
private static final int DISCOVER_DURATION = 300;
Context context;
ArrayAdapter mArrayAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//set the user interface layout for this activity
setRetainInstance(false);
View v = inflater.inflate(R.layout.activity_bluetooth_transfer, parent, false);
context = this.getActivity();
filePathTextView = (TextView) v.findViewById(R.id.file_path_textView);
startTransferButton = (Button) v.findViewById(R.id.start_transfer_button);
bluetoothImage = (ImageView) v.findViewById(R.id.bluetooth_imageView);
bluetoothImage.setClickable(true);
startTransferButton.setOnClickListener(new View.OnClickListener() {
//start transfer processes
#SuppressWarnings("unchecked")
#Override
public void onClick(View v){
//check to make sure the file path text view != null
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
int REQUEST_ENABLE_BT = -1;
//ensure the device being used has bluetooth capability
if (btAdapter != null){
//check-enable bluetooth
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//ensure the textview isn't empty
//check if filepath is null
if (filePathTextView.getText().toString().length() != 0){
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
//check if there are paired devices
if (pairedDevices.size() > 0){
//loop through paired devices
for (BluetoothDevice device: pairedDevices){
//add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}//end found paired devices if
// Create a BroadcastReceiver for ACTION_FOUND
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());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//COMPILER ERROR BELOW ######################################################
//"This method registerReceiver(BroadcastReceiver, IntentFilter)
//is undefined for type new View.OnClickListener
registerReceiver(mReceiver, filter);
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
btAdapter.cancelDiscovery();
}//
else {
//alert user to input file path
new AlertDialog.Builder(context).setTitle("Error")
.setMessage("Please insert a filename to send.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
}).show();
}//ifnull (else)
}//bt equipped check
}//end anon class
});
bluetoothImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//display dialog showing program specs and creators
new AlertDialog.Builder(context).setTitle("About")
.setMessage("Created by:"+"\n"+ "Hal, Chris, and Roger")
.setPositiveButton("Awesome!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
});
return v;
}
}
TransferActivity:
package com.project.BluetoothTransfer_v1000;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class TransferActivity extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transfer);
TransferFragment fragment = new TransferFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();
}
}
Try:
TransferFragment.this.getActivity().registerReceiver(mReceiver, filter);
Instead of:
registerReceiver(mReceiver, filter);
Because the method registerReceiver is part of the Activity and not the OnClickListener. This is why the error message complains about not found method in OnClickListener:
This method registerReceiver(BroadcastReceiver, IntentFilter)
is undefined for type new View.OnClickListener
This is totally in sane, I got my app working 100% (it's only listing devices not doing any connection) but when i execute it it doesnt appear any Bluetooth device in my ListView, the funniest part is that when I execute it with debugger they DO appear. Here you have my code, I have been looking at it for the last 3 hours, hope you can land me a hand :(
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ListarDispositivos extends ListActivity {
//this, R.layout.activity_listar_dispositivos, s
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private static String EXTRA_DEVICE_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listar_dispositivos);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.nombres_dispositivos,R.id.txvNombreDispositivo);
ListView listview = getListView();
setListAdapter(mNewDevicesArrayAdapter);
//listview.setOnItemClickListener(mDeviceClickListener);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
doDiscovery();
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
mBtAdapter.disable();
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
private void doDiscovery() {
// Indicate scanning in the title
setTitle("Escaneando");
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
Toast toast1 =
Toast.makeText(getApplicationContext(),
"Estoy buscando", Toast.LENGTH_SHORT);
toast1.show();
}
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);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
//Salta cada vez que encuentra un dispositivo o eso deberia el cabron
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)) {
setTitle("Elija dispositivo");
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = "No encontrado";
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.listar_dispositivos, menu);
return true;
}
}
After adding found devices to the mNewDevicesArrayAdapter, you should call notifyDataSetChanged() so that the listview is refreshed.
I am developing an application where I have to connect to a Bluetooth device.
When I click the btn_discover Button, it will call BroadcastReceiver and scan the new bluetooth device and show on the TextView.
When I use the TextView, I can see the bluetooth device on Textview.
And now I want to change the TextView to ListView.
But it always crashes. When in BroadcastReceiver's onReceive(), I write:
newDevicelistArrayAdapter.add(device.getName());
This is my Java Code:
package com.example.bttest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import com.example.bttest.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity {
public BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_SELECT_DEVICE = 1;
public Button btn_scan;
public Button btn_discover;
public TextView pair_list;
public TextView scan_list;
public ListView scan_list_1;
public Set<BluetoothDevice> pairedDevices;
public ArrayAdapter<String> newDevicelistArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_scan = (Button)findViewById(R.id.btn_scan);
btn_discover = (Button)findViewById(R.id.btn_discover);
pair_list = (TextView)findViewById(R.id.pair_list);
scan_list = (TextView)findViewById(R.id.scan_list);
newDevicelistArrayAdapter = new ArrayAdapter<String>(this, R.layout.main);
scan_list_1 = (ListView)findViewById(R.id.scan_list_1);
scan_list_1.setAdapter(newDevicelistArrayAdapter);
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);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
}
});
}
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");
newDevicelistArrayAdapter.add(device.getName());
}
}
};
protected void onDestroy() {
super.onDestroy();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
#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;
}
}
Does it any wrong when I use the ListView and ArrayAdapter?
Replace the onReceive() of your BroadcastReceiver with this:
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");
newDevicelistArrayAdapter.notifyDataSetChanged();
}
}