Skip to main content

Bluetooth Device Searching

MainActivity.java


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.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

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.activity_main);
     
        btnScanDevice = (Button)findViewById(R.id.scandevice);
     
        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
     
        listDevicesFound = (ListView)findViewById(R.id.devicesfound);
        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));
    }
 
    @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());
             btArrayAdapter.notifyDataSetChanged();
    }
  }
  };
 
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:id="@+id/bluetoothstate"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
<TextView
    android:id="@+id/bluetoothstate"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
<Button
    android:id="@+id/scandevice"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Scan Bluetooth Devices"
    android:enabled="false"
    />
<ListView
    android:id="@+id/devicesfound"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
</LinearLayout>

Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluetooth_search"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
 <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.bluetooth_search.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Comments

  1. I am a new developer and i was trying just to copy that code to try it but i get a problem in MainActivity.java where it says "import android.app.Activity;"
    The problem is:
    The declared package "" does not match the expected package "com.example.bluetooth_search"

    i suppose it is just a silly thing but cannot fix it!
    you know what could it be?
    thanks!

    ReplyDelete

Post a Comment

Popular posts from this blog

Bluetooth Chat Example

Manifest File <manifest xmlns:android="http://schemas.android.com/apk/res/android"       package="com.example.android.BluetoothChat"       android:versionCode="1"       android:versionName="1.0">     <uses-sdk minSdkVersion="7" />     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />     <uses-permission android:name="android.permission.BLUETOOTH" />     <application android:label="@string/app_name"                  android:icon="@drawable/app_icon" >         <activity android:name=".BluetoothChat"                   android:label="@string/app_name"                   android:configChanges="orientation|keyboardHidden">             <intent-filter> ...

Custom TextView With Images in Android

Create a custom XML Tag with image and text 1) Class extends Textview import java . util . regex . Matcher ; import java . util . regex . Pattern ; import android . content . Context ; import android . text . Spannable ; import android . text . style . ImageSpan ; import android . util . AttributeSet ; import android . util . Log ; import android . widget . TextView ; public class TextViewWithImages extends TextView { public TextViewWithImages ( Context context , AttributeSet attrs , int defStyle ) { super ( context , attrs , defStyle ); } public TextViewWithImages ( Context context , AttributeSet attrs ) { super ( context , attrs ); } public TextViewWithImages ( Context context ) { super ( context ); } @Override public void setText ( CharSequence text , BufferType type ) { Spannable s = getTextWithImages ( getContext (), text ); super . setText...

AcceleroMeter Sensors with SurfaceMovements on Canvas

MainActivity.java import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class MainActivity extends Activity implements SensorEventListener { float x, y, sensorX, sensorY; Bitmap ball; SensorManager sm; Sensor s; MyBringBackSurface ourSurfaceView; /**  * Canvas Movement  */ public class MyBringBackSurface extends SurfaceView implements Runnable {     SurfaceHolder ourHolder;     Thread ourThread = null;     boolean isRunning = false;     public MyBringBackSurface(Context context) {         super(context)...