手机蓝牙连接配对源码(安卓手机蓝牙配对)
本文目录一览:
- 1、通过android代码如何实现手机蓝牙自动连接最后一次已配对的设备
- 2、如何实现android蓝牙开发 自动配对连接,并不弹出提示框
- 3、手机蓝牙怎么配对连接?
- 4、如何实现android蓝牙自动配对连接
- 5、android_studio手机蓝牙串口通信源代码
- 6、如何实现Android蓝牙开发 自动配对连接,并不弹出提示框
通过android代码如何实现手机蓝牙自动连接最后一次已配对的设备
先明确场景。你是希望如下哪种自动连接?
case1: 手机开机自动连接蓝牙最后配对设备:Android已经在Framework层实现。不需要Apk再做。关键代码如下:
BluetoothDeviceConnectionPolicy.java 里面
onReceive 收到事件BluetoothAdapter.STATE_ON后
else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
initiateConnection();给状态机发CONNECT
mBluetoothAutoConnectStateMachine.sendMessage(BluetoothAutoConnectStateMachine.CONNECT);
case2:蓝牙关闭状态,打开蓝牙,自动连接最后使用的设备:Apk层注册监听蓝牙打开的广播,然后在事件响应中获取已配对列表,取第一个去进行连接就好。
注册监听蓝牙打开的广播事件:android.bluetooth.adapter.action.STATE_CHANGED
Bluetooth ACTION_STATE_CHANGED curState = 11,preState = 10 打开中
Bluetooth ACTION_STATE_CHANGED curState = 12,preState = 11 打开了。
获取已配对设备列表:BluetoothAdapter.getBondedDevices()
取出第一个设备(也就是最新的),连接:
framework/base/core/java/android/bluetooth/
BluetoothHeadsetClient: connect(device)
BluetoothA2dpSink: connect(device)
如何实现android蓝牙开发 自动配对连接,并不弹出提示框
android蓝牙自动配对连接的具体代码如下: 1. 获取蓝牙适配器BluetoothAdapter blueadapter=BluetoothAdapter.getDefaultAdapter(); 如果BluetoothAdapter 为null,说明android手机没有蓝牙模块。 2. 判断蓝牙模块是否开启,blueadapter.isEnabled() true表示已经开启,false表示蓝牙并没启用。 3. 启动配置蓝牙可见模式,即进入可配对模式Intent in=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); in.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200); startActivity(in); ,200就表示200秒。 4. 获取蓝牙适配器中已经配对的设备SetBluetoothDevice device=blueadapter.getBondedDevices(); 当然,还需要在androidManifest.xml中声明蓝牙的权限 uses-permission android:name="android.permission.BLUETOOTH" / uses-permission android:name="android.permission.BLUETOOTH_ADMIN" / 5.自动配对设置Pin值 static public boolean autoBond(Class btClass, BluetoothDevice device, String strPin) throws Exception { Method autoBondMethod = btClass.getMethod("setPin", new Class[] { byte[].class }
手机蓝牙怎么配对连接?
准备工具:iphone7。
系统版本:ios12。
1、首先打开手机设置。如下图所示:
2、进入界面后点击蓝牙。如下图所示:
3、打开蓝牙功能。
4、然后就可以搜索附近的蓝牙了,点击要连接的蓝牙会自动配对。
5、最后配对成功。
如何实现android蓝牙自动配对连接
望你踩呐我的回答
下面是自动配对的代码
Mainfest,xml注册
receiver android:name=".BluetoothConnectActivityReceiver"
intent-filter
action android:name="android.bluetooth.device.action.PAIRING_REQUEST" /
/intent-filter
/receiver
自己在收到广播时处理并将预先输入的密码设置进去
public class BluetoothConnectActivityReceiver 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
执行时直接使用:
bpublic 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_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-permission android:name="android.permission.BLUETOOTH"/uses-permission
uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/uses-permission
下面附上Android蓝牙操作中用固定MAC地址传输信息的模板,通用搜索模式日后再补删模板:
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //这条是蓝牙串口通用的UUID,不要更改
private static String address = "00:12:02:22:06:61"; // ==要连接的蓝牙设备MAC地址
/*获得通信线路过程*/
/*1:获取本地BlueToothAdapter*/
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
Toast.makeText(this, "Bluetooth is not available.", Toast.LENGTH_LONG).show();
finish();
return;
}
if(!mBluetoothAdapter.isEnabled())
{
Toast.makeText(this, "Please enable your Bluetooth and re-run this program.", Toast.LENGTH_LONG).show();
finish();
return;
}
/*2:获取远程BlueToothDevice*/
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if(mBluetoothAdapter == null)
{
Toast.makeText(this, "Can't get remote device.", Toast.LENGTH_LONG).show();
finish();
return;
}
/*3:获得Socket*/
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Socket creation failed.", e);
}
/*4:取消discovered节省资源*/
mBluetoothAdapter.cancelDiscovery();
/*5:连接*/
try {
btSocket.connect();
Log.e(TAG, "ON RESUME: BT connection established, data transfer link open.");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
}
}
/*此时可以通信了,放在任意函数中*/
/* try {
outStream = btSocket.getOutputStream();
inStream = btSocket.getInputStream(); //可在TextView里显示
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}
String message = "1";
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
*/
通用搜索模式代码模板:
简洁简洁方式1 demo
作用: 用VerticalSeekBar控制一个 LED屏幕的亮暗。
直接上码咯~
package com.example.seed2;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
public class MetalSeed extends Activity {
private static final String TAG = "BluetoothTest";
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
private VerticalSeekBar vskb = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //这条是蓝牙串口通用的UUID,不要更改
private static String address = "00:12:02:22:06:61"; // ==要连接的蓝牙设备MAC地址
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.vskb = (VerticalSeekBar)super.findViewById(R.id.mskb);
this.vskb.setOnSeekBarChangeListener(new OnSeekBarChangeListenerX());
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
Toast.makeText(this, "Bluetooth is not available.", Toast.LENGTH_LONG).show();
finish();
return;
}
if(!mBluetoothAdapter.isEnabled())
{
Toast.makeText(this, "Please enable your Bluetooth and re-run this program.", Toast.LENGTH_LONG).show();
finish();
return;
}
}
private class OnSeekBarChangeListenerX implements VerticalSeekBar.OnSeekBarChangeListener {
public void onProgressChanged(VerticalSeekBar seekBar, int progress, boolean fromUser) {
//Main.this.clue.setText(seekBar.getProgress());
/* String message;
byte [] msgBuffer;
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG,"ON RESUME : Output Stream creation failed.", e);
}
message =Integer.toString( seekBar.getProgress() );
msgBuffer = message.getBytes();
try{
outStream.write(msgBuffer);
} catch (IOException e) {
Log.e (TAG, "ON RESUME : Exception during write.", e);
} */
}
public void onStartTrackingTouch(VerticalSeekBar seekBar) {
String message;
byte [] msgBuffer;
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG,"ON RESUME : Output Stream creation failed.", e);
}
message =Integer.toString( seekBar.getProgress() );
msgBuffer = message.getBytes();
try{
outStream.write(msgBuffer);
} catch (IOException e) {
Log.e (TAG, "ON RESUME : Exception during write.", e);
}
}
public void onStopTrackingTouch(VerticalSeekBar seekBar) {
String message;
byte [] msgBuffer;
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG,"ON RESUME : Output Stream creation failed.", e);
}
message =Integer.toString( seekBar.getProgress() );
msgBuffer = message.getBytes();
try{
outStream.write(msgBuffer);
} catch (IOException e) {
Log.e (TAG, "ON RESUME : Exception during write.", e);
}
}
}
@Override
public void onStart()
{
super.onStart();
}
@Override
public void onResume()
{
super.onResume();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Socket creation failed.", e);
}
mBluetoothAdapter.cancelDiscovery();
try {
btSocket.connect();
Log.e(TAG, "ON RESUME: BT connection established, data transfer link open.");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
}
}
// Create a data stream so we can talk to server.
/* try {
outStream = btSocket.getOutputStream();
inStream = btSocket.getInputStream();
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}
String message = "read";
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
int ret = -1;
while( ret != -1)
{
try {
ret = inStream.read();
} catch (IOException e)
{
e.printStackTrace();
}
}
*/
}
@Override
如何实现Android蓝牙开发 自动配对连接,并不弹出提示框
实现android蓝牙开发 自动配对连接,并不弹出提示框: 源码 BluetoothDevice 类中还有两个隐藏方法:cancelBondProcess()和cancelPairingUserInput(),这两个方法一个是取消配对进程一个是取消用户输入 下面是自动配对的代码 Mainfest,xml注册 receiver android:name=".BluetoothConnectActivityReceiver" intent-filter action android:name="android.bluetooth.device.action.PAIRING_REQUEST" / /intent-filter /receiver自己在收到广播时处理并将预先输入的密码设置进去public class BluetoothConnectActivityReceiver 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执行时直接使用:bpublic 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 blockLog.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; }