当前位置:首页 » 安卓系统 » 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,相对来说比较新,用的话主要是理解一些新的协议栈概念,不是很难,网上资料相对来说少些,你也可以找找看

热点内容
图片文字识别算法 发布:2025-05-16 20:21:54 浏览:45
校园ftp服务器 发布:2025-05-16 20:19:38 浏览:71
数据加密技术的实现 发布:2025-05-16 20:12:49 浏览:158
华为p9扩存储 发布:2025-05-16 20:03:22 浏览:414
如何用苹果ipad登录安卓微信 发布:2025-05-16 19:58:51 浏览:139
预编译error技巧 发布:2025-05-16 19:57:42 浏览:779
php地址正则表达式 发布:2025-05-16 19:44:01 浏览:467
oracle存储过程优点 发布:2025-05-16 19:41:36 浏览:614
无法访问g盘拒绝访问 发布:2025-05-16 19:32:57 浏览:119
阿里云服务器如何把c盘变成d盘 发布:2025-05-16 19:12:36 浏览:497