public abstract class

BluetoothConnector

extends Object
java.lang.Object
   ↳ mobisocial.nfc.addon.BluetoothConnector

Class Overview

Allows two devices to establish a Bluetooth connection after exchanging an NFC Connection Handover Request. The socket is returned via callback.

A simple example for establishing a Bluetooth connection when both phones are in the same activity:

 MyActivity extends Activity {
   Nfc mNfc;
   
   BluetoothConnector.OnConnectedListener mBtListener =
           new BluetoothConnector.OnConnectedListener() {
       
       public void onConnectionEstablished(BluetoothSocket socket, 
               boolean isServer) {
          Log.d(TAG, "Connected over Bluetooth as " +
              (isServer ? "server" : "client"));
       }
   }
   
   public void onCreate(Bundle bundle) {
     super.onCreate(bundle);
     mNfc = new Nfc(this);
     BluetoothConnector.prepare(mNfc, mBtListener);
   }

   public void onResume() {
     super.onResume();
     mNfc.onResume(this);
   }
   
   public void onPause() {
     super.onPause();
     mNfc.onPause();
   }
   
   public void onNewInent(Intent intent) {
     if (mNfc.onNewIntent(this, intent)) return;
   }
 }
 

A more complex example, which supports:

  • Pairing when both phones are in the same activity
  • Pairing when only one phone is in the activity
  • Providing a download link if your application is not yet installed.

You should also ensure that Bluetooth and Nfc are enabled on the device.

 public class MyActivity extends Activity {
  private Nfc mNfc;
  private Long mLastPausedMillis = 0L;

  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      mNfc = new Nfc(this);

      // If this activity was launched from an NFC interaction, start the
      // Bluetooth connection process.
      if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
          BluetoothConnector.join(mNfc, mBluetoothConnected, getNdefMessages(getIntent())[0]);
      } else {
          // If both phones are running this activity, or to allow remote
          // device to join from home screen.
          BluetoothConnector.prepare(mNfc, mBluetoothConnected, getAppReference());
      }
  }

  protected void onResume() {
      super.onResume();
      mNfc.onResume(this);
  }

  protected void onPause() {
      super.onPause();
      mLastPausedMillis = System.currentTimeMillis();
      mNfc.onPause(this);
  }

  protected void onNewIntent(Intent intent) {
      // Check for "warm boot" if the activity uses singleInstance launch mode:
      if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
          Long ms = System.currentTimeMillis() - mLastPausedMillis;
          if (ms > 150) {
              BluetoothConnector.join(mNfc, mBluetoothConnected, getNdefMessages(intent)[0]);
              return;
          }
      }
      if (mNfc.onNewIntent(this, intent)) {
          return;
      }
  }

  public NdefRecord[] getAppReference() {
      byte[] urlBytes = "http://example.com/funapp".getBytes();
      NdefRecord ref = new NdefRecord(NdefRecord.TNF_ABSOLUTE_URI, NdefRecord.RTD_URI, new byte[]{}, urlBytes);
      return new NdefRecord[] { ref };
  }

  OnConnectedListener mBluetoothConnected = new OnConnectedListener() {
      public void onConnectionEstablished(BluetoothSocket socket, boolean isServer) {
          toast("connected! server: " + isServer);
      }
  };

  private void toast(final String text) {
      runOnUiThread(new Runnable() {
          public void run() {
              Toast.makeText(MyActivity.this, text, Toast.LENGTH_SHORT).show();
          }
      });
  }

  private NdefMessage[] getNdefMessages(Intent intent) {
      if (!intent.hasExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)) {
          return null;
      }
      Parcelable[] msgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
      NdefMessage[] ndef = new NdefMessage[msgs.length];
      for (int i = 0; i < msgs.length; i++) {
          ndef[i] = (NdefMessage) msgs[i];
      }
      return ndef;
  }
 }
 
You will also need to add an intent filter to your application's manifest:
   <activity android:name=".MyActivity">
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="http"
                  android:host="example.com"
                  android:path="/funapp" />
        </intent-filter>
   </activity>
 
For devices supporting SDK 14 and above, the handover record also includes an Android Application Record, allowing your application to be discovered in the market if it is not yet installed. Otherwise, the uri provided by getAppReference() should direct the user to a web page relevant to your application.

Summary

Nested Classes
interface BluetoothConnector.OnConnectedListener A callback used when a Bluetooth connection has been established. 
Public Constructors
BluetoothConnector()
Public Methods
static void join(Nfc nfc, BluetoothConnector.OnConnectedListener conn, NdefMessage ndef)
Extracts the Bluetooth socket information from an ndef message and connects as a client.
static BluetoothServerSocket prepare(Nfc nfc, BluetoothConnector.OnConnectedListener conn)
Configures the Nfc interface to set up a Bluetooth socket with another device.
static BluetoothServerSocket prepare(Nfc nfc, BluetoothConnector.OnConnectedListener conn, NdefRecord[] ndef)
Configures the Nfc interface to set up a Bluetooth socket with another device.
[Expand]
Inherited Methods
From class java.lang.Object

Public Constructors

public BluetoothConnector ()

Public Methods

public static void join (Nfc nfc, BluetoothConnector.OnConnectedListener conn, NdefMessage ndef)

Extracts the Bluetooth socket information from an ndef message and connects as a client.

public static BluetoothServerSocket prepare (Nfc nfc, BluetoothConnector.OnConnectedListener conn)

Configures the Nfc interface to set up a Bluetooth socket with another device. The method both sets the foreground ndef messages and registers an NdefHandler to look for incoming pairing requests.

When this method is called, a Bluetooth server socket is created, and the socket is closed after a successful connection. You must call prepare() again to reinitiate the server socket.

Returns
  • The server socket listening for peers.

public static BluetoothServerSocket prepare (Nfc nfc, BluetoothConnector.OnConnectedListener conn, NdefRecord[] ndef)

Configures the Nfc interface to set up a Bluetooth socket with another device. The method both sets the foreground ndef messages and registers an NdefHandler to look for incoming pairing requests.

When this method is called, a Bluetooth server socket is created, and the socket is closed after a successful connection. You must call prepare() again to reinitiate the server socket.

Returns
  • The server socket listening for peers.