I'm new here so I apologize if I wrote something bad
I got some error in my code that should find some but device (in Eclipse it looks ok but it shows some Force Quit while I'm clicking button Find Device :(
Code
package com.moj.test;
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.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Bluetooth extends Activity{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth);
Button bStart = (Button) findViewById(R.id.btbutton1);
Button bFind = (Button) findViewById(R.id.btbutton2);
bStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BluetoothStart();
}
});
bFind.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
mBluetoothAdapter.startDiscovery();
}
});
}
public void BluetoothStart() {
if (mBluetoothAdapter != null) {
if (!mBluetoothAdapter.isEnabled()) {
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_ENABLE_BT);
}
}
}
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
EditText te = (EditText) findViewById(R.id.editText1);
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
te.setText(device.getName() + "\n" + device.getAddress());
}
}
};
}
You cant run this on Emulator because it doesn't have support for Bluetooth. You need to test it on a real device.
And don't forget to include Bluetooth permission in manifest.
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
...
</manifest>
Related
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. :)
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
I'm working on android application. In my project I want to show Bluetooth scanning device, MAC Address, Bluetooth signal strength and Distance between two Android device.
I have done 3 requirements but I don't know how to get distance using Signal strength.
package com.example.bluetoothdemo;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.BroadcastReceiver;
public class MainActivity extends Activity {
private BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();
private static final int REQUEST_ENABLE_BT = 1;
ListView listDevicesFound;
Button btnScanDevice;
TextView stateBluetooth;
BluetoothAdapter bluetoothAdapter;
ArrayAdapter<String> btArrayAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnScanDevice = (Button)findViewById(R.id.scan_device);
stateBluetooth = (TextView)findViewById(R.id.textView1);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listDevicesFound = (ListView)findViewById(R.id.listView1);
btArrayAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1);
listDevicesFound.setAdapter(btArrayAdapter);
CheckBlueToothState();
btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);
registerReceiver(ActionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(ActionFoundReceiver);
}
private void CheckBlueToothState(){
if (bluetoothAdapter == null){
stateBluetooth.setText("Bluetooth NOT support");
}else{
if (bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.isDiscovering()){
stateBluetooth.setText("Bluetooth is currently in device discovery process.");
}else{
stateBluetooth.setText("Bluetooth is Enabled.");
btnScanDevice.setEnabled(true);
}
}else{
stateBluetooth.setText("Bluetooth is NOT Enabled!");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private Button.OnClickListener btnScanDeviceOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
btArrayAdapter.clear();
bluetoothAdapter.startDiscovery();
}};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
CheckBlueToothState();
}
}
private final BroadcastReceiver ActionFoundReceiver = 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);
btArrayAdapter.add(device.getName() + "\n" + device.getAddress()+ "
\n "+intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE));
btArrayAdapter.notifyDataSetChanged();
}
}};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private final BroadcastReceiver receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
TextView rssi_msg = (TextView) findViewById(R.id.listView1);
Toast.makeText(getApplicationContext()," RSSI: " + rssi + "dBm",
Toast.LENGTH_SHORT).show();
}
}
};
}
Try using the "b and l bluetooth le scanner" app from the Google Play Store, to visualize the signals from several Bluetooth LE devices. You will immediately discover that the rssi signal strengths are "noisy" when multiple devices are present. Walls, furniture with metal components, and Wi-Fi sources will also cause signal variations. The best solution is to create "zones" for your distance readings... Something like: far, close, next-to, etc.
That is practically not possible to calculate the distance based on only the bluetooth signal strength. You can however use the triangulation technique to get the distance between the two devices or altogether can use the GPS concept to find out the distance.
Using only bluetooth, finding distance is not possible.
Even though you can do something like this to denote the signal strength in an easy understandable way.
https://play.google.com/store/apps/details?id=com.bluetoothFinder
see this link.
You can calculate distance by using txPower. Below is a mathematical way to calculate this.
double getDistance(int rssi, int txPower) {
return Math.pow(10d, ((double) txPower - rssi) / (10 * 2));
}
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();
}
}
I am trying to make an android bluetooth printer application, in which I am successful in detecting bluetooth devices in my proximity,but I am not able to set up a connection when one of the device is choose for connection. also as I am trying to get names of devices in a listview,it is showing one name many times. I am posting my code below.please help
package com.example.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import android.os.Bundle;
import android.os.Handler;
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.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
OutputStream mmOutputStream;
ListView listDevicesFound;
Button btnScanDevice,connect;
TextView stateBluetooth;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
List<String> discoverableDevicesList;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
ArrayAdapter<String> btArrayAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnScanDevice = (Button)findViewById(R.id.scandevice);
stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
connect = (Button)findViewById(R.id.button2);
listDevicesFound = (ListView)findViewById(R.id.devicesfound);
btArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listDevicesFound.setAdapter(btArrayAdapter);
CheckBlueToothState();
btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);
registerReceiver(ActionFoundReceiver,
new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(ActionFoundReceiver);
}
private void CheckBlueToothState(){
if (mBluetoothAdapter == null){
stateBluetooth.setText("Bluetooth NOT support");
}else{
if (mBluetoothAdapter.isEnabled()){
if(mBluetoothAdapter.isDiscovering()){
stateBluetooth.setText("Bluetooth is currently in device discovery process.");
}else{
stateBluetooth.setText("Bluetooth is Enabled.");
btnScanDevice.setEnabled(true);
}
}else{
stateBluetooth.setText("Bluetooth is NOT Enabled!");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private Button.OnClickListener btnScanDeviceOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
btArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
}};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
CheckBlueToothState();
}
}
private final BroadcastReceiver ActionFoundReceiver = 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);
btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}
};}
This is Dialog to show all Paired devices in ListView.
public Dialog pushDevicePairDialog(){
_mDeviceListView = ((LayoutInflater) _mCallingActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.bluetooth_devices_list, null, false);
_mDeviceListDialog = new Dialog(_mCallingActivity,R.style.ThemeDialogCustom);
_mDeviceListDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
_mDeviceListDialog.setContentView(_mDeviceListView);
_mDeviceListDialog.setCancelable(true);
_mPairedDevicesArrayAdapter = new ArrayAdapter<String>(_mCallingActivity,R.layout.device_name);
_mNewDevicesArrayAdapter = new ArrayAdapter<String>(_mCallingActivity,R.layout.device_name);
Button scanButton = (Button) _mDeviceListView.findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});
ListView pairedListView = (ListView) _mDeviceListView.findViewById(R.id.paired_devices);
pairedListView.setAdapter(_mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(_mDeviceClickListener);
ListView newDevicesListView = (ListView) _mDeviceListView.findViewById(R.id.new_devices);
newDevicesListView.setAdapter(_mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(_mDeviceClickListener);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
_mCallingActivity.registerReceiver(_mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
_mCallingActivity.registerReceiver(_mReceiver, filter);
_mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = _mBtAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
_mDeviceListView.findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
String devName = device.getName();
if(devName != null && (devName.startsWith("ESYS") || devName.startsWith("ACC")))
_mPairedDevicesArrayAdapter.add(devName + "\n" + device.getAddress());
}
} else {
String noDevices = _mCallingActivity.getResources().getText(R.string.none_paired).toString();
_mPairedDevicesArrayAdapter.add(noDevices);
}
if (_mBluetoothService == null)
_mBluetoothService = new BluetoothConnectorService(_mCallingActivity);
_mBluetoothService.setListener(this);
return _mDeviceListDialog;
}