ALFA DeV工作室原創文章如轉載,請注明:轉載自博客原文位址:HTTP://blog.csdn.net/kongre/article/details/6737288

藍牙是一種在鄰近的設備之間進行資料傳輸的開放無線協定。如果想使用藍牙協定在手機上進行資料傳輸的話,首先需要開啟手機的藍牙服務,然後去尋找鄰近的開啟藍牙服務的設備進行配對,配對成功之後,即可進行資料傳輸。如果在我們的Android應用程式需要使用Smart Phone的藍牙服務,需要在我們的專案清單檔AndroidManifest.xml聲明使用相應的許可權。



Html代碼
<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>

 

<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>

 

android framework將有關藍牙功能的API放在android.bluetooth包中。其中有五個比較關鍵的類,分別是

 

1.BluetoothAdapter: 主要用來尋找設備和初始化藍牙服務的

 

2.BluetoothClass:主要用來描述藍牙設備

 

3.BluetoothDevice:代表一個鄰近的藍牙設備

 

4.BluetoothSocket:代表的是與其他藍牙設備進行資料傳輸的連接點

 

5.BluetoothServerSokcet:代表一個對配對請求進行監聽的服務端通訊端

 

接下來會對這些關鍵類進行分析和使用。

 

秘笈一、如何打開藍牙服務(先關閉測試真機藍牙服務)



JAVA代碼
public class BluetoothActivity extends Activity {
@SuppressWarnings("unused")
private Button mTurnOnBluetooth, mDiscoverDevices, mPairWithBondedDevices, mOpenSocket;

 

private BluetoothAdapter myBluetooth = null;//尋找藍牙設備和初始化藍牙連接
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

 

mTurnOnBluetooth = (Button)findViewById(R.id.turnOnBluetooth);
mDiscoverDevices = (Button)findViewById(R.id.discoverBluetoothDevices);
mPairWithBondedDevices = (Button)findViewById(R.id.pairWithBondedDevices);
mOpenSocket = (Button)findViewById(R.id.openSocket);

 

mTurnOnBluetooth.setOnClickListener(new OnClickListener() {

 

@Override
public void onClick(View v) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if( !myBluetooth.isEnabled()){//如果沒有開啟藍牙服務,啟動內置Activity請求使用者打開藍牙服務
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBluetoothIntent);
}
}
});
}
}

 

public class BluetoothActivity extends Activity {
@SuppressWarnings("unused")
private Button mTurnOnBluetooth, mDiscoverDevices, mPairWithBondedDevices, mOpenSocket;

 

private BluetoothAdapter myBluetooth = null;//尋找藍牙設備和初始化藍牙連接
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

 

mTurnOnBluetooth = (Button)findViewById(R.id.turnOnBluetooth);
mDiscoverDevices = (Button)findViewById(R.id.discoverBluetoothDevices);
mPairWithBondedDevices = (Button)findViewById(R.id.pairWithBondedDevices);
mOpenSocket = (Button)findViewById(R.id.openSocket);

 

mTurnOnBluetooth.setOnClickListener(new OnClickListener() {

 

@Override
public void onClick(View v) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if( !myBluetooth.isEnabled()){//如果沒有開啟藍牙服務,啟動內置Activity請求使用者打開藍牙服務
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBluetoothIntent);
}
}
});
}
}程式說明:BluetoothAdapter用來初始化藍牙服務, 靜態方法getDefaultAdapter()方法獲取藍牙服務的相關資訊.如果方法返回null值,說明此手機不支援藍牙服務。如果此時藍牙服務沒有被啟動,那麼可以使用內置Activity:BluetoothAdapter.ACTION_REQUEST_ENABLE來請求使用者是否對應用程式進行授權,從而決定是否打開藍牙服務。真機運行效果圖如下:




秘笈二、尋找設備



JAVA代碼
public class BluetoothActivity extends Activity {

 

private static String TAG = "BluetoothActivity";

 

@SuppressWarnings("unused")
private Button mTurnOnBluetooth, mDiscoverDevices, mPairWithBondedDevices, mOpenSocket;

 

private BluetoothAdapter myBluetooth = null;//尋找藍牙設備和初始化藍牙連接

 

//定義廣播接收者接受尋找到藍牙設備或者曾經配對設備之後的系統廣播
private final BroadcastReceiver mReceiver = 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);
Log.d(TAG, "name:" + device.getName() + "\t address:" + device.getAddress());
}
}
};

 

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

 

mTurnOnBluetooth = (Button)findViewById(R.id.turnOnBluetooth);
mDiscoverDevices = (Button)findViewById(R.id.discoverBluetoothDevices);
mPairWithBondedDevices = (Button)findViewById(R.id.pairWithBondedDevices);
mOpenSocket = (Button)findViewById(R.id.openSocket);

//打開藍牙服務
mTurnOnBluetooth.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if( !myBluetooth.isEnabled()){//如果沒有開啟藍牙服務,啟動內置Activity請求使用者打開藍牙服務
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBluetoothIntent);
}
}
});


//尋找設備
mDiscoverDevices.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
myBluetooth.startDiscovery();
}
});
}
}

public class BluetoothActivity extends Activity {

private static String TAG = "BluetoothActivity";

@SuppressWarnings("unused")
private Button mTurnOnBluetooth, mDiscoverDevices, mPairWithBondedDevices, mOpenSocket;

private BluetoothAdapter myBluetooth = null;//尋找藍牙設備和初始化藍牙連接

//定義廣播接收者接受尋找到藍牙設備或者曾經配對設備之後的系統廣播
private final BroadcastReceiver mReceiver = 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);
Log.d(TAG, "name:" + device.getName() + "\t address:" + device.getAddress());
}
}
};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mTurnOnBluetooth = (Button)findViewById(R.id.turnOnBluetooth);
mDiscoverDevices = (Button)findViewById(R.id.discoverBluetoothDevices);
mPairWithBondedDevices = (Button)findViewById(R.id.pairWithBondedDevices);
mOpenSocket = (Button)findViewById(R.id.openSocket);

//打開藍牙服務
mTurnOnBluetooth.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if( !myBluetooth.isEnabled()){//如果沒有開啟藍牙服務,啟動內置Activity請求使用者打開藍牙服務
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBluetoothIntent);
}
}
});


//尋找設備
mDiscoverDevices.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
myBluetooth.startDiscovery();
}
});
}
}程式說明:在藍牙服務被啟動之後,用BluetoothAdapter的實例物件可以用來尋找附近的藍牙設備,通過調用startDiscovery()方法。注意,這是一個非同步調用方法。所以需要註冊相應的廣播接收者對BluetoothDevice.ACTION_FOUND系統廣播進行接受,無論在何時只要一尋找到鄰近的藍牙設備就發送此系統廣播。當然你也可以對ACTION_DISCOVERY_STARTED和ACTION_DISCOVERY_FINISHED系統廣播進行接受,從而告訴應用程式什麼時候尋找開始,什麼時候尋找結束了。測試真機LOG日誌如下:





秘笈三、打開一個藍牙的Socket

跟JAVA的TCP程式設計其實是一個道理。

服務端執行緒:


JAVA代碼
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;

public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = myBluetooth.listenUsingRfcommWithServiceRecord("test",
randomUUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}

@Override
public void run() {
super.run();
BluetoothSocket socket = null;
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
if (socket != null) {
// do some work to communication
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}

}
}
}

private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;

public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = myBluetooth.listenUsingRfcommWithServiceRecord("test",
randomUUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}

@Override
public void run() {
super.run();
BluetoothSocket socket = null;
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
if (socket != null) {
// do some work to communication
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}

}
}
}用戶端執行緒:


JAVA代碼
@SuppressWarnings("unused")
private class ConnectThread extends Thread{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device){
BluetoothSocket tmp = null;
mmDevice = device;
//get a BluetoothSocket to connect with the given BluetoothDevice
//randomUUID is the app's UUID String, also used by the server code
try{
tmp = device.createRfcommSocketToServiceRecord(randomUUID);
}catch(IOException e){

}
mmSocket = tmp;
}

@Override
public void run() {
super.run();
myBluetooth.cancelDiscovery();//cancel the discovery because it will slow down the connection
try{
mmSocket.connect();//connect the device through the socket . This will block until it succeeds or throws an exception
}catch(IOException connectionException){
try {
mmSocket.close();//unable to connect ;close the socket and get out
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}

//do some work to communication
}
}

@SuppressWarnings("unused")
private class ConnectThread extends Thread{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device){
BluetoothSocket tmp = null;
mmDevice = device;
//get a BluetoothSocket to connect with the given BluetoothDevice
//randomUUID is the app's UUID String, also used by the server code
try{
tmp = device.createRfcommSocketToServiceRecord(randomUUID);
}catch(IOException e){

}
mmSocket = tmp;
}

@Override
public void run() {
super.run();
myBluetooth.cancelDiscovery();//cancel the discovery because it will slow down the connection
try{
mmSocket.connect();//connect the device through the socket . This will block until it succeeds or throws an exception
}catch(IOException connectionException){
try {
mmSocket.close();//unable to connect ;close the socket and get out
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}

//do some work to communication
}
}




上述大致介紹了有關Android Bluetooth使用的相關內容和細節,相信大家都已經掌握了相關知識。

最後如果你還是覺得我寫的不夠詳細 看的不夠爽 不要緊我把原始程式碼的下載位址貼出來 歡迎大家一起討論學習ALFA DeV工作室希望可以和大家一起進步。

下載位址:HTTP://download.csdn.net/source/3565226
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()