當前位置:首頁 » 安卓系統 » android藍牙源碼

android藍牙源碼

發布時間: 2022-06-17 19:08:58

⑴ 如何實現android藍牙自動配對連接

望你踩吶我的回答

下面是自動配對的代碼
Mainfest,xml注冊
<receiver android:name="." >
<intent-filter>
<action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
</intent-filter>
</receiver>

自己在收到廣播時處理並將預先輸入的密碼設置進去

public class extends BroadcastReceiver
{

String strPsw = "0";

@Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
if (intent.getAction().equals(
"android.bluetooth.device.action.PAIRING_REQUEST"))
{
BluetoothDevice btDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

// byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234");
// device.setPin(pinBytes);
Log.i("tag11111", "ddd");
try
{
ClsUtils.setPin(btDevice.getClass(), btDevice, strPsw); // 手機和藍牙採集器配對
ClsUtils.createBond(btDevice.getClass(), btDevice);
ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

<b>/************************************ 藍牙配對函數 * **************/
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.bluetooth.BluetoothDevice;
import android.util.Log;
public class ClsUtils
{

/**
* 與設備配對 參考源碼:platform/packages/apps/Settings.git
* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
*/
static public boolean createBond(Class btClass, BluetoothDevice btDevice)
throws Exception
{
Method createBondMethod = btClass.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}

/**
* 與設備解除配對 參考源碼:platform/packages/apps/Settings.git
* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
*/
static public boolean removeBond(Class btClass, BluetoothDevice btDevice)
throws Exception
{
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}

static public boolean setPin(Class btClass, BluetoothDevice btDevice,
String str) throws Exception
{
try
{
Method removeBondMethod = btClass.getDeclaredMethod("setPin",
new Class[]
{byte[].class});
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,
new Object[]
{str.getBytes()});
Log.e("returnValue", "" + returnValue);
}
catch (SecurityException e)
{
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;

}

// 取消用戶輸入
static public boolean cancelPairingUserInput(Class btClass,
BluetoothDevice device)

throws Exception
{
Method createBondMethod = btClass.getMethod("cancelPairingUserInput");
// cancelBondProcess()
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
return returnValue.booleanValue();
}

// 取消配對
static public boolean cancelBondProcess(Class btClass,
BluetoothDevice device)

throws Exception
{
Method createBondMethod = btClass.getMethod("cancelBondProcess");
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
return returnValue.booleanValue();
}

/**
*
* @param clsShow
*/
static public void printAllInform(Class clsShow)
{
try
{
// 取得所有方法
Method[] hideMethod = clsShow.getMethods();
int i = 0;
for (; i < hideMethod.length; i++)
{
Log.e("method name", hideMethod[i].getName() + ";and the i is:"
+ i);
}
// 取得所有常量
Field[] allFields = clsShow.getFields();
for (i = 0; i < allFields.length; i++)
{
Log.e("Field name", allFields[i].getName());
}
}
catch (SecurityException e)
{
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}</b>

執行時直接使用:

<b>public static boolean pair(String strAddr, String strPsw)
{
boolean result = false;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();

bluetoothAdapter.cancelDiscovery();

if (!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
}

if (!BluetoothAdapter.checkBluetoothAddress(strAddr))
{ // 檢查藍牙地址是否有效

Log.d("mylog", "devAdd un effient!");
}

BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr);

if (device.getBondState() != BluetoothDevice.BOND_BONDED)
{
try
{
Log.d("mylog", "NOT BOND_BONDED");
ClsUtils.setPin(device.getClass(), device, strPsw); // 手機和藍牙採集器配對
ClsUtils.createBond(device.getClass(), device);
remoteDevice = device; // 配對完畢就把這個設備對象傳給全局的remoteDevice
result = true;
}
catch (Exception e)
{
// TODO Auto-generated catch block

Log.d("mylog", "setPiN failed!");
e.printStackTrace();
} //

}
else
{
Log.d("mylog", "HAS BOND_BONDED");
try
{
ClsUtils.createBond(device.getClass(), device);
ClsUtils.setPin(device.getClass(), device, strPsw); // 手機和藍牙採集器配對
ClsUtils.createBond(device.getClass(), device);
remoteDevice = device; // 如果綁定成功,就直接把這個設備對象傳給全局的remoteDevice
result = true;
}
catch (Exception e)
{
// TODO Auto-generated catch block
Log.d("mylog", "setPiN failed!");
e.printStackTrace();
}
}
return result;
}</b>

⑵ Android藍牙開發代碼怎麼寫

開啟藍牙設備和設置可見時間:

privatevoidsearch(){
BluetoothAdapteradapter=BluetoothAdapter.getDefaultAdapter();
if(!adapter.isEnabled()){
adapter.enable();
}
Intentenable=newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,3600);//3600為藍牙設備可見時間
startActivity(enable);
IntentsearchIntent=newIntent(this,ComminuteActivity.class);
startActivity(searchIntent);
}

首先,需要獲得一個BluetoothAdapter,可以通過getDefaultAdapter()獲得系統默認的藍牙適配器,當然我們也可以自己指定,但這個真心沒有必要,至少我是不需要的。然後我們檢查手機的藍牙是否打開,如果沒有,通過enable()方法打開。接著我們再設置手機藍牙設備的可見,可見時間可以自定義。

http://www.cnblogs.com/wenjiang/p/3200138.html

⑶ 誰能給一份開發基於藍牙4.0的android的demo源碼

請參考如下WIKI頁面,基本上目前有提供的BLE的參考代碼都集中到這個頁面了:http://processors.wiki.ti.com/index.php/Category:BluetoothLE

⑷ 如何實現android藍牙開發 自動配對連接,並不彈出提示框

我就開始查找怎麼關閉這個藍牙配對提示框,後面還是偉大的android源碼幫助了我。
在源碼 BluetoothDevice 類中還有兩個隱藏方法
cancelBondProcess()和cancelPairingUserInput()
這兩個方法一個是取消配對進程一個是取消用戶輸入
下面是自動配對的代碼
Mainfest,xml注冊

<receiverandroid:name=".">

<intent-filter>

<actionandroid:name="android.bluetooth.device.action.PAIRING_REQUEST"/>

</intent-filter>

</receiver>

自己在收到廣播時處理並將預先輸入的密碼設置進去


{

StringstrPsw="0";

@Override
publicvoidonReceive(Contextcontext,Intentintent)
{
//TODOAuto-generatedmethodstub
if(intent.getAction().equals(
"android.bluetooth.device.action.PAIRING_REQUEST"))
{
BluetoothDevicebtDevice=intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

//byte[]pinBytes=BluetoothDevice.convertPinToBytes("1234");
//device.setPin(pinBytes);
Log.i("tag11111","ddd");
try
{
ClsUtils.setPin(btDevice.getClass(),btDevice,strPsw);//手機和藍牙採集器配對
ClsUtils.createBond(btDevice.getClass(),btDevice);
ClsUtils.cancelPairingUserInput(btDevice.getClass(),btDevice);
}
catch(Exceptione)
{
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}


}
}
<b>/************************************藍牙配對函數***************/
importjava.lang.reflect.Field;
importjava.lang.reflect.Method;

importandroid.bluetooth.BluetoothDevice;
importandroid.util.Log;
publicclassClsUtils
{

/**
*與設備配對參考源碼:platform/packages/apps/Settings.git
*/Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
*/
staticpublicbooleancreateBond(ClassbtClass,BluetoothDevicebtDevice)
throwsException
{
MethodcreateBondMethod=btClass.getMethod("createBond");
BooleanreturnValue=(Boolean)createBondMethod.invoke(btDevice);
returnreturnValue.booleanValue();
}

/**
*與設備解除配對參考源碼:platform/packages/apps/Settings.git
*/Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
*/
staticpublicbooleanremoveBond(ClassbtClass,BluetoothDevicebtDevice)
throwsException
{
MethodremoveBondMethod=btClass.getMethod("removeBond");
BooleanreturnValue=(Boolean)removeBondMethod.invoke(btDevice);
returnreturnValue.booleanValue();
}

staticpublicbooleansetPin(ClassbtClass,BluetoothDevicebtDevice,
Stringstr)throwsException
{
try
{
MethodremoveBondMethod=btClass.getDeclaredMethod("setPin",
newClass[]
{byte[].class});
BooleanreturnValue=(Boolean)removeBondMethod.invoke(btDevice,
newObject[]
{str.getBytes()});
Log.e("returnValue",""+returnValue);
}
catch(SecurityExceptione)
{
//thrownewRuntimeException(e.getMessage());
e.printStackTrace();
}
catch(IllegalArgumentExceptione)
{
//thrownewRuntimeException(e.getMessage());
e.printStackTrace();
}
catch(Exceptione)
{
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returntrue;

}

//取消用戶輸入
(ClassbtClass,
BluetoothDevicedevice)

throwsException
{
MethodcreateBondMethod=btClass.getMethod("cancelPairingUserInput");
//cancelBondProcess()
BooleanreturnValue=(Boolean)createBondMethod.invoke(device);
returnreturnValue.booleanValue();
}

//取消配對
(ClassbtClass,
BluetoothDevicedevice)

throwsException
{
MethodcreateBondMethod=btClass.getMethod("cancelBondProcess");
BooleanreturnValue=(Boolean)createBondMethod.invoke(device);
returnreturnValue.booleanValue();
}

/**
*
*@paramclsShow
*/
(ClassclsShow)
{
try
{
//取得所有方法
Method[]hideMethod=clsShow.getMethods();
inti=0;
for(;i<hideMethod.length;i++)
{
Log.e("methodname",hideMethod[i].getName()+";andtheiis:"
+i);
}
//取得所有常量
Field[]allFields=clsShow.getFields();
for(i=0;i<allFields.length;i++)
{
Log.e("Fieldname",allFields[i].getName());
}
}
catch(SecurityExceptione)
{
//thrownewRuntimeException(e.getMessage());
e.printStackTrace();
}
catch(IllegalArgumentExceptione)
{
//thrownewRuntimeException(e.getMessage());
e.printStackTrace();
}
catch(Exceptione)
{
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}</b>
執行時直接使用:
<b>publicstaticbooleanpair(StringstrAddr,StringstrPsw)
{
booleanresult=false;
=BluetoothAdapter
.getDefaultAdapter();

bluetoothAdapter.cancelDiscovery();

if(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
}

if(!BluetoothAdapter.checkBluetoothAddress(strAddr))
{//檢查藍牙地址是否有效

Log.d("mylog","devAdneffient!");
}

BluetoothDevicedevice=bluetoothAdapter.getRemoteDevice(strAddr);

if(device.getBondState()!=BluetoothDevice.BOND_BONDED)
{
try
{
Log.d("mylog","NOTBOND_BONDED");
ClsUtils.setPin(device.getClass(),device,strPsw);//手機和藍牙採集器配對
ClsUtils.createBond(device.getClass(),device);
remoteDevice=device;//配對完畢就把這個設備對象傳給全局的remoteDevice
result=true;
}
catch(Exceptione)
{
//TODOAuto-generatedcatchblock

Log.d("mylog","setPiNfailed!");
e.printStackTrace();
}//

}
else
{
Log.d("mylog","HASBOND_BONDED");
try
{
ClsUtils.createBond(device.getClass(),device);
ClsUtils.setPin(device.getClass(),device,strPsw);//手機和藍牙採集器配對
ClsUtils.createBond(device.getClass(),device);
remoteDevice=device;//如果綁定成功,就直接把這個設備對象傳給全局的remoteDevice
result=true;
}
catch(Exceptione)
{
//TODOAuto-generatedcatchblock
Log.d("mylog","setPiNfailed!");
e.printStackTrace();
}
}
returnresult;
}</b>

⑸ 關於android系統藍牙都用什麼模塊,有單獨的android驅動嗎

Android系統的源碼中藍牙部分的分布式這樣的:
1. App部分主要包括OPP和PBAP以及HFP,當然還有settings部分,代碼分布如下:
(1) /packages/app/Bluetooth/src/com/android/bluetooth/opp
(2) /packages/app/Bluetooth/src/com/android/bluetooth/pbap
(3) /packages/app/Phone/src/com/android/phone/ 中和BT相關的部分,主要是HFHS打電話相關的
(4) /packages/app/Settings/src/com/android/settings/bluetooth/ 主要是藍牙開啟,搜索,配對等

2. Framework部分主要包括BluetoothAdapter,BluetoothService,BluetoothEventLoop,BluetoothA2dpService等核心類,代碼分布如下:
(1)/frameworks/base/core/java/android/server/ 包含BluetoothService,BluetoothEventLoop等核心類,但是並沒有向用戶應用程序提供介面,屬於系統的類。
(2)/frameworks/base/core/java/android/bluetooth 包含了BluetoothAdapter, BluetoothSocket, BluetoothServerSocket等一系列類,這些類是系統向應用程序提供的介面,編寫藍牙相關的應用程序時會用到這些類,檢查BT是否打開,搜索設備等等。如果編寫藍牙應用程序,需要熟悉該部分類的功能。
(3) /frameworks/base/core/jni/ 中包含Bluetooth相關的文件,如 android_server_BluetoothService.cpp 該部分主要是java層和c/c++層進行通信的

3. Bluez部分,主要包括各個協議的實現,如A2dp,AVRCP,AVDTP,HID,HDP,PAN,DUN以及對BT host的實現,通過該部分向BT Controler部分發送HCI命令,代碼分布服下:
/external/bluetooth/bluez

4. BluetDroid部分,主要用於開關藍牙,晶元上電部分(不屬於驅動,可以算是硬體抽象層(HAL)), 代碼分布如下:
/system/bluetooth/

5. kernel部分,主要包括RFCOMM,L2CAP等協議以及HCI的實現,代碼分布如下:
/kernel/net/bluetooth/

6. driver部分,該部分代碼還真沒了解過,代碼分布:
/kernel/drivers/bluetooth/
另外,driver部分和具體晶元密切相關,有時在下面的目錄下也會有:
/vendor/
/device/

⑹ 求android 藍牙開發的示例代碼 主要是怎麼搜索其他設備 然後以列表的形勢顯示出來,急求~!!!

看源碼就行了,很簡單的。

⑺ 如何實現Android藍牙開發 自動配對連接,並不彈出提示框

實現android藍牙開發 自動配對連接,並不彈出提示框: 源碼 BluetoothDevice 類中還有兩個隱藏方法:cancelBondProcess()和cancelPairingUserInput(),這兩個方法一個是取消配對進程一個是取消用戶輸入 下面是自動配對的代碼 Mainfest,xml注冊 <receiver android:name="." > <intent-filter> <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" /> </intent-filter> </receiver> 自己在收到廣播時處理並將預先輸入的密碼設置進去 public class extends BroadcastReceiver { String strPsw = "0"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if (intent.getAction().equals( "android.bluetooth.device.action.PAIRING_REQUEST")) { BluetoothDevice btDevice = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234"); // device.setPin(pinBytes); Log.i("tag11111", "ddd"); try { ClsUtils.setPin(btDevice.getClass(), btDevice, strPsw); // 手機和藍牙採集器配對 ClsUtils.createBond(btDevice.getClass(), btDevice); ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } <b>/************************************ 藍牙配對函數 * **************/ import java.lang.reflect.Field; import java.lang.reflect.Method; import android.bluetooth.BluetoothDevice; import android.util.Log; public class ClsUtils { /** * 與設備配對 參考源碼:platform/packages/apps/Settings.git * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java */ static public boolean createBond(Class btClass, BluetoothDevice btDevice) throws Exception { Method createBondMethod = btClass.getMethod("createBond"); Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice); return returnValue.booleanValue(); } /** * 與設備解除配對 參考源碼:platform/packages/apps/Settings.git * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java */ static public boolean removeBond(Class btClass, BluetoothDevice btDevice) throws Exception { Method removeBondMethod = btClass.getMethod("removeBond"); Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice); return returnValue.booleanValue(); } static public boolean setPin(Class btClass, BluetoothDevice btDevice, String str) throws Exception { try { Method removeBondMethod = btClass.getDeclaredMethod("setPin", new Class[] {byte[].class}); Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice, new Object[] {str.getBytes()}); Log.e("returnValue", "" + returnValue); } catch (SecurityException e) { // throw new RuntimeException(e.getMessage()); e.printStackTrace(); } catch (IllegalArgumentException e) { // throw new RuntimeException(e.getMessage()); e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } // 取消用戶輸入 static public boolean cancelPairingUserInput(Class btClass, BluetoothDevice device) throws Exception { Method createBondMethod = btClass.getMethod("cancelPairingUserInput"); // cancelBondProcess() Boolean returnValue = (Boolean) createBondMethod.invoke(device); return returnValue.booleanValue(); } // 取消配對 static public boolean cancelBondProcess(Class btClass, BluetoothDevice device) throws Exception { Method createBondMethod = btClass.getMethod("cancelBondProcess"); Boolean returnValue = (Boolean) createBondMethod.invoke(device); return returnValue.booleanValue(); } /** * * @param clsShow */ static public void printAllInform(Class clsShow) { try { // 取得所有方法 Method[] hideMethod = clsShow.getMethods(); int i = 0; for (; i < hideMethod.length; i++) { Log.e("method name", hideMethod[i].getName() + ";and the i is:" + i); } // 取得所有常量 Field[] allFields = clsShow.getFields(); for (i = 0; i < allFields.length; i++) { Log.e("Field name", allFields[i].getName()); } } catch (SecurityException e) { // throw new RuntimeException(e.getMessage()); e.printStackTrace(); } catch (IllegalArgumentException e) { // throw new RuntimeException(e.getMessage()); e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }</b> 執行時直接使用: <b>public static boolean pair(String strAddr, String strPsw) { boolean result = false; BluetoothAdapter bluetoothAdapter = BluetoothAdapter .getDefaultAdapter(); bluetoothAdapter.cancelDiscovery(); if (!bluetoothAdapter.isEnabled()) { bluetoothAdapter.enable(); } if (!BluetoothAdapter.checkBluetoothAddress(strAddr)) { // 檢查藍牙地址是否有效 Log.d("mylog", "devAdd un effient!"); } BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { try { Log.d("mylog", "NOT BOND_BONDED"); ClsUtils.setPin(device.getClass(), device, strPsw); // 手機和藍牙採集器配對 ClsUtils.createBond(device.getClass(), device); remoteDevice = device; // 配對完畢就把這個設備對象傳給全局的remoteDevice result = true; } catch (Exception e) { // TODO Auto-generated catch block Log.d("mylog", "setPiN failed!"); e.printStackTrace(); } // } else { Log.d("mylog", "HAS BOND_BONDED"); try { ClsUtils.createBond(device.getClass(), device); ClsUtils.setPin(device.getClass(), device, strPsw); // 手機和藍牙採集器配對 ClsUtils.createBond(device.getClass(), device); remoteDevice = device; // 如果綁定成功,就直接把這個設備對象傳給全局的remoteDevice result = true; } catch (Exception e) { // TODO Auto-generated catch block Log.d("mylog", "setPiN failed!"); e.printStackTrace(); } } return result; }

⑻ 求安卓Android手機上的的藍牙串口通訊源碼!!!!

http://code.eoe.cn/789?f_section=new
以上是地址 自己去下

⑼ android_studio手機藍牙串口通信源代碼

初涉android的藍牙操作,按照固定MAC地址連接獲取Device時,程序始終是異常終止,查了好多天代碼都沒查出原因。今天改了一下API版本,突然就成功連接了。總結之後發現果然是個坑爹之極的錯誤。

為了這種錯誤拚命查原因浪費大把時間是非常不值得的,但是問題不解決更是揪心。可惜我網路了那麼多,都沒有給出確切原因。今天特此mark,希望後來者遇到這個問題的時候能輕松解決。

下面是我的連接過程,中間崩潰原因及解決辦法。

1:用AT指令獲得藍牙串口的MAC地址,地址是簡寫的,按照常理猜測可得標准格式。

2:開一個String adress= "************" //MAC地址, String MY_UUID= "************"//UUID根據通信而定,網上都有。

3:取得本地Adapter用getDefaultAdapter(); 遠程的則用getRemoteDevice(adress); 之後便可用UUID開socket進行通信。

如果中途各種在getRemoteDevice處崩潰,大家可以查看一下當前的API版本,如果是2.1或以下版本的話,便能確定是API版本問題,只要換成2.2或者以上就都可以正常運行了~ 這么坑爹的錯誤的確很為難初學者。 唉·········· 為這種小trick浪費很多時間真是難過。

(另外有個重要地方,別忘了給manifest裡面加以下兩個藍牙操作許可權哦~)

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

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

  • 下面附上Android藍牙操作中用固定MAC地址傳輸信息的模板,通用搜索模式日後再補刪模板:

  • =null;

  • =null;

  • privateOutputStreamoutStream=null;

  • privateInputStreaminStream=null;

  • privatestaticfinalUUIDMY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//這條是藍牙串口通用的UUID,不要更改

  • privatestaticStringaddress="00:12:02:22:06:61";//<==要連接的藍牙設備MAC地址

  • /*獲得通信線路過程*/

  • /*1:獲取本地BlueToothAdapter*/

  • mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

  • if(mBluetoothAdapter==null)

  • {

  • Toast.makeText(this,"Bluetoothisnotavailable.",Toast.LENGTH_LONG).show();

  • finish();

  • return;

  • }

  • if(!mBluetoothAdapter.isEnabled())

  • {

  • Toast.makeText(this,"-runthisprogram.",Toast.LENGTH_LONG).show();

  • finish();

  • return;

  • }

  • /*2:獲取遠程BlueToothDevice*/

  • BluetoothDevicedevice=mBluetoothAdapter.getRemoteDevice(address);

  • if(mBluetoothAdapter==null)

  • {

  • Toast.makeText(this,"Can'tgetremotedevice.",Toast.LENGTH_LONG).show();

  • finish();

  • return;

  • }

  • /*3:獲得Socket*/

  • try{

  • btSocket=device.(MY_UUID);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Socketcreationfailed.",e);

  • }

  • /*4:取消discovered節省資源*/

  • mBluetoothAdapter.cancelDiscovery();

  • /*5:連接*/

  • try{

  • btSocket.connect();

  • Log.e(TAG,"ONRESUME:BTconnectionestablished,datatransferlinkopen.");

  • }catch(IOExceptione){

  • try{

  • btSocket.close();

  • }catch(IOExceptione2){

  • Log.e(TAG,"ONRESUME:",e2);

  • }

  • }

  • /*此時可以通信了,放在任意函數中*/

  • /*try{

  • outStream=btSocket.getOutputStream();

  • inStream=btSocket.getInputStream();//可在TextView里顯示

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Outputstreamcreationfailed.",e);

  • }

  • Stringmessage="1";

  • byte[]msgBuffer=message.getBytes();

  • try{

  • outStream.write(msgBuffer);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);

  • }

  • */

  • 通用搜索模式代碼模板:

    簡潔簡潔方式1 demo


    作用: 用VerticalSeekBar控制一個 LED屏幕的亮暗。

    直接上碼咯~

  • packagecom.example.seed2;

  • importandroid.app.Activity;

  • importandroid.app.AlertDialog;

  • importandroid.app.Dialog;

  • importandroid.os.Bundle;

  • importjava.io.IOException;

  • importjava.io.InputStream;

  • importjava.io.OutputStream;

  • importjava.util.UUID;

  • importandroid.bluetooth.BluetoothAdapter;

  • importandroid.bluetooth.BluetoothDevice;

  • importandroid.bluetooth.BluetoothSocket;

  • importandroid.content.DialogInterface;

  • importandroid.util.Log;

  • importandroid.view.KeyEvent;

  • importandroid.widget.Toast;

  • {

  • privatestaticfinalStringTAG="BluetoothTest";

  • =null;

  • =null;

  • privateOutputStreamoutStream=null;

  • privateInputStreaminStream=null;

  • privateVerticalSeekBarvskb=null;

  • privatestaticfinalUUIDMY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//這條是藍牙串口通用的UUID,不要更改

  • privatestaticStringaddress="00:12:02:22:06:61";//<==要連接的藍牙設備MAC地址

  • /**.*/

  • @Override

  • publicvoidonCreate(BundlesavedInstanceState){

  • super.onCreate(savedInstanceState);

  • setContentView(R.layout.main);

  • this.vskb=(VerticalSeekBar)super.findViewById(R.id.mskb);

  • this.vskb.setOnSeekBarChangeListener(newOnSeekBarChangeListenerX());

  • mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

  • if(mBluetoothAdapter==null)

  • {

  • Toast.makeText(this,"Bluetoothisnotavailable.",Toast.LENGTH_LONG).show();

  • finish();

  • return;

  • }

  • if(!mBluetoothAdapter.isEnabled())

  • {

  • Toast.makeText(this,"-runthisprogram.",Toast.LENGTH_LONG).show();

  • finish();

  • return;

  • }

  • }

  • .OnSeekBarChangeListener{

  • publicvoidonProgressChanged(VerticalSeekBarseekBar,intprogress,booleanfromUser){

  • //Main.this.clue.setText(seekBar.getProgress());

  • /*Stringmessage;

  • byte[]msgBuffer;

  • try{

  • outStream=btSocket.getOutputStream();

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:OutputStreamcreationfailed.",e);

  • }

  • message=Integer.toString(seekBar.getProgress());

  • msgBuffer=message.getBytes();

  • try{

  • outStream.write(msgBuffer);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);

  • }*/

  • }

  • (VerticalSeekBarseekBar){

  • Stringmessage;

  • byte[]msgBuffer;

  • try{

  • outStream=btSocket.getOutputStream();

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:OutputStreamcreationfailed.",e);

  • }

  • message=Integer.toString(seekBar.getProgress());

  • msgBuffer=message.getBytes();

  • try{

  • outStream.write(msgBuffer);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);

  • }

  • }

  • publicvoidonStopTrackingTouch(VerticalSeekBarseekBar){

  • Stringmessage;

  • byte[]msgBuffer;

  • try{

  • outStream=btSocket.getOutputStream();

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:OutputStreamcreationfailed.",e);

  • }

  • message=Integer.toString(seekBar.getProgress());

  • msgBuffer=message.getBytes();

  • try{

  • outStream.write(msgBuffer);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);

  • }

  • }

  • }

  • @Override

  • publicvoidonStart()

  • {

  • super.onStart();

  • }

  • @Override

  • publicvoidonResume()

  • {

  • super.onResume();

  • BluetoothDevicedevice=mBluetoothAdapter.getRemoteDevice(address);

  • try{

  • btSocket=device.(MY_UUID);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Socketcreationfailed.",e);

  • }

  • mBluetoothAdapter.cancelDiscovery();

  • try{

  • btSocket.connect();

  • Log.e(TAG,"ONRESUME:BTconnectionestablished,datatransferlinkopen.");

  • }catch(IOExceptione){

  • try{

  • btSocket.close();

  • }catch(IOExceptione2){

  • Log.e(TAG,"ONRESUME:",e2);

  • }

  • }

  • //.

  • /*try{

  • outStream=btSocket.getOutputStream();

  • inStream=btSocket.getInputStream();

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Outputstreamcreationfailed.",e);

  • }

  • Stringmessage="read";

  • byte[]msgBuffer=message.getBytes();

  • try{

  • outStream.write(msgBuffer);

  • }catch(IOExceptione){

  • Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);

  • }

  • intret=-1;

  • while(ret!=-1)

  • {

  • try{

  • ret=inStream.read();

  • }catch(IOExceptione)

  • {

  • e.printStackTrace();

  • }

  • }

  • */

  • }

  • @Override

⑽ Android源碼中有關藍牙配對的程序在哪些文件中

你是用的藍牙2.0,還是4.0 BLE?不管是這兩者中哪一個,android SDK都有相關sample可以學習使用,從搜索設備,建立連接,到兩端的通信都有,基本覆蓋我們要使用的所有功能。
2.0的sample是:BluetoothChat,里邊有3個.java文件,網上對它的相關講解很多,你可以參考blog.csdn.net/homebei2/article/details/6078007;
4.0的sample是:BluetoothLeGatt,如果我沒記錯的話,里邊有4個.java文件,因為google在android4.3才支持BLE的api,相對來說比較新,用的話主要是理解一些新的協議棧概念,不是很難,網上資料相對來說少些,你也可以找找看

熱點內容
java任務管理 發布:2025-05-16 22:17:02 瀏覽:571
安卓如何修改cpu 發布:2025-05-16 21:58:20 瀏覽:364
pythonainb 發布:2025-05-16 21:45:56 瀏覽:855
淘汰伺服器可以做家用電腦嗎 發布:2025-05-16 21:41:31 瀏覽:842
遊程編碼c語言 發布:2025-05-16 21:26:51 瀏覽:587
帝來哪個配置值得購買 發布:2025-05-16 21:12:29 瀏覽:463
什麼是nodejs前端伺服器 發布:2025-05-16 21:12:17 瀏覽:405
編譯選項立即綁定未定義符號 發布:2025-05-16 20:55:13 瀏覽:907
linuxmysql慢日誌 發布:2025-05-16 20:47:58 瀏覽:272
村兩委有哪些配置 發布:2025-05-16 20:34:47 瀏覽:294