Android,蓝牙配对后仅通过身份验证交换信息 //

2023-12-13

我想通过蓝牙与仅通过身份验证配对的 2 个 Android 设备交换一些信息。我已经在 Android 开发人员端看到了 Android 聊天示例示例。它运行良好,但现在我想要在 2 个设备的蓝牙配对后,想要相互交换一些信息,就像当设备将其一些信息发送到其他设备时,远程设备上会出现身份验证弹出窗口,如果接受,则仅与另一方共享信息...vv 感谢 adv....

using below code i also want to show authentication before pairing 2 devices via     Bluetooth..but it directly pair without any authentication send to other side 

下面是从 Android 开发人员端获取的 BluetoothChatService.jave 代码

public class BluetoothChatService extends Activity {
    // Debugging
    private static final String TAG = "BluetoothChatService";
    private static final boolean D = true;
    // Name for the SDP record when creating server socket
    private static final String NAME = "BluetoothChat";
    // Unique UUID for this application
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
            // ("fa87c0d0-afac-11de-8a39-0800200c9a66");
    // Member fields
    private final BluetoothAdapter mAdapter;
    private final Handler mHandler;
    private AcceptThread mAcceptThread;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private int mState;
    // Constants that indicate the current connection state
    public static final int STATE_NONE = 0; // we're doing nothing
    public static final int STATE_LISTEN = 1; // now listening for incoming
    // connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing
    // connection
    public static final int STATE_CONNECTED = 3; // now connected to a remote
    // device

    /**
     * Constructor. Prepares a new BluetoothChat session.
     * 
     * @param context
     *            The UI Activity Context
     * @param handler
     *            A Handler to send messages back to the UI Activity
     */
    public BluetoothChatService(Context context, Handler handler) {
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mState = STATE_NONE;
        mHandler = handler;
    }

    /**
     * Set the current state of the chat connection
     * 
     * @param state
     *            An integer defining the current connection state
     */
    private synchronized void setState(int state) {
        if (D) {
            Log.d(TAG, "setState() " + mState + " -> " + state);
        }
        mState = state;

        // Give the new state to the Handler so the UI Activity can update
        mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1)
                .sendToTarget();
    }

    /**
     * Return the current connection state.
     */
    public synchronized int getState() {
        return mState;
    }

    /**
     * Start the chat service. Specifically start AcceptThread to begin a
     * session in listening (server) mode. Called by the Activity onResume()
     */
    public synchronized void start() {
        if (D) {
            Log.d(TAG, "start");
        }

        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }

        // Start the thread to listen on a BluetoothServerSocket
        if (mAcceptThread == null) {
            mAcceptThread = new AcceptThread();
            mAcceptThread.start();
        }
        setState(STATE_LISTEN);
    }

    /**
     * Start the ConnectThread to initiate a connection to a remote device.
     * 
     * @param device
     *            The BluetoothDevice to connect
     */
    public synchronized void connect(BluetoothDevice device) {
        if (D) {
            Log.d(TAG, "connect to: " + device);
        }

        // Cancel any thread attempting to make a connection
        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {
                mConnectThread.cancel();
                mConnectThread = null;
            }
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }

        // Start the thread to connect with the given device
        mConnectThread = new ConnectThread(device);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    }

    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * 
     * @param socket
     *            The BluetoothSocket on which the connection was made
     * @param device
     *            The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket,
            BluetoothDevice device) {
        if (D) {
            Log.d(TAG, "connected");
        }

        // Cancel the thread that completed the connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }

        // Cancel the accept thread because we only want to connect to one
        // device
        if (mAcceptThread != null) {
            mAcceptThread.cancel();
            mAcceptThread = null;
        }

        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();

        // Send the name of the connected device back to the UI Activity
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
        msg.setData(bundle);
        mHandler.sendMessage(msg);

        setState(STATE_CONNECTED);
    }

    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (D) {
            Log.d(TAG, "stop");
        }
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        if (mAcceptThread != null) {
            mAcceptThread.cancel();
            mAcceptThread = null;
        }
        setState(STATE_NONE);
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * 
     * @param out
     *            The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (mState != STATE_CONNECTED) {
                return;
            }
            r = mConnectedThread;
        }
        // Perform the write unsynchronized
        r.write(out);
    }

    /**
     * Indicate that the connection attempt failed and notify the UI Activity.
     */
    private void connectionFailed() {
        setState(STATE_LISTEN);

        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.TOAST, "Unable to connect device");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
        setState(STATE_LISTEN);
        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.TOAST, "Device connection was lost");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

/**
 * This thread runs while listening for incoming connections. It behaves
 * like a server-side client. It runs until a connection is accepted (or
 * until cancelled).
 */
private class AcceptThread extends Thread {
    // The local server socket
    private final BluetoothServerSocket mmServerSocket;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;

        // Create a new listening server socket
        try {

            tmp = mAdapter
                    .listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
//                if(!tmp.toString().equalsIgnoreCase(null)){

//              
  //          }
        } catch (IOException e) {
            Log.e(TAG, "listen() failed", e);
        }
        mmServerSocket = tmp;
    }

    @Override
    public void run() {
        if (D) {
            Log.d(TAG, "BEGIN mAcceptThread" + this);
        }
        setName("AcceptThread");
        BluetoothSocket socket = null;

        // Listen to the server socket if we're not connected
        while (mState != STATE_CONNECTED) {


                try {
                    socket = mmServerSocket.accept();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }


            // If a connection was accepted
            if (socket != null) {
                synchronized (BluetoothChatService.this) {
                    switch (mState) {
                    case STATE_LISTEN:
                    case STATE_CONNECTING:
                        // Situation normal. Start the connected thread.
                        connected(socket, socket.getRemoteDevice());
                        break;
                    case STATE_NONE:
                    case STATE_CONNECTED:
                        // Either not ready or already connected. Terminate
                        // new socket.
                        try {
                            socket.close();
                        } catch (IOException e) {
                            Log.e(TAG,"Could not close unwanted socket",
                                            e);
                        }
                        break;
                    }
                }
            }
        }
        if (D) {
            Log.i(TAG, "END mAcceptThread");
        }
    }

    public void cancel() {
        if (D) {
            Log.d(TAG, "cancel " + this);
        }
        try {
            mmServerSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of server failed", e);
        }
    }
}

/**
 * This thread runs while attempting to make an outgoing connection with a
 * device. It runs straight through; the connection either succeeds or
 * fails.
 */
private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;

    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        mmDevice = device;
        BluetoothSocket tmp = null;


        try {
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mmSocket = tmp;
    }

    @Override
    public void run() {
        Log.i(TAG, "BEGIN mConnectThread");
        setName("ConnectThread");

        // Always cancel discovery because it will slow down a connection
        mAdapter.cancelDiscovery();

        // Make a connection to the BluetoothSocket
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            mmSocket.connect();
        } catch (IOException e) {
            connectionFailed();
            // Close the socket
            try {
                mmSocket.close();
            } catch (IOException e2) {
                Log.e(TAG,"unable to close() socket during connection failure",
                                e2);
            }
            // Start the service over to restart listening mode
            BluetoothChatService.this.start();
            return;
        }

        // Reset the ConnectThread because we're done
        synchronized (BluetoothChatService.this) {
            mConnectThread = null;
        }

        // Start the connected thread
        connected(mmSocket, mmDevice);
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
        }
    }
}

/**
 * This thread runs during a connection with a remote device. It handles all
 * incoming and outgoing transmissions.
 */
private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;

    private final InputStream mmInStream;

    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        Log.d(TAG, "create ConnectedThread");
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    @Override
    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];
        int bytes;

        // Keep listening to the InputStream while connected
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);

                // Send the obtained bytes to the UI Activity

                // XXX !!!
                String buffer2 = new String(buffer);
                buffer2= buffer2.substring(0, buffer2.length()-3)+"\n";

                mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes,
                        -1, buffer2.getBytes()).sendToTarget();

            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }

    /**
     * Write to the connected OutStream.
     * 
     * @param buffer
     *            The bytes to write
     */
    public void write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);

            // Share the sent message back to the UI Activity

            // XXX !!!
            String buffer2 = new String(buffer);
            buffer2= buffer2.substring(0, buffer2.length()-2);
            mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1,
                    buffer2.getBytes()).sendToTarget();

        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
        }
    }
}

None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android,蓝牙配对后仅通过身份验证交换信息 // 的相关文章

随机推荐

  • 将键盘表情符号转换为自定义 png,反之亦然

    这是一个直接而简单的问题 我怎样才能实现这两件事 FIRST 输入 嘿我在微笑 输出 hey I m smiling span class smile span 反之亦然 SECOND 输入 嘿我在微笑 smile 输出 嘿我在微笑 现在我
  • 无法在无服务器和 DynamoDB/Cognito/API 网关的 lambda 策略中使用 ${cognito-identity.amazonaws.com:sub}

    客观的 使用 Cognito 进行身份验证 使用下面的 serverless yml 配置 点击经过身份验证的端点 GET users 以触发 lambda 作业 基于IAM策略 限制基于cognito用户查询的DynamoDB表的访问co
  • 比较旋转图像

    我正在寻找一种方法来比较几乎相同 相似度超过 95 但可以绕中心轴旋转的图像 我对整个计算机图形 视觉领域很陌生 不太确定是否有现成的工具或系统 或者即使这是否是正确的堆栈交换 目前 我正在研究使用 C 生成位图直方图 然后通过 Panda
  • VBA:为什么我的 INSERT 代码不起作用?

    几周前我就开始工作了 但现在我不确定我做了什么导致它不再工作了 我什至没有收到错误消息来弄清楚可能出了什么问题 当我单击在表中插入行的按钮时 没有任何反应 表单被清除并重新查询表 但代码的 INSERT 部分不执行任何操作 Public S
  • 如何将文件从一个位置复制到另一个位置?

    我想在 Java 中将文件从一个位置复制到另一个位置 做这个的最好方式是什么 这是我到目前为止所拥有的 import java io File import java io FilenameFilter import java util A
  • Powershell运行时

    我在 Windows 8 下运行 VS 2010 安装 NuGet 并运行包管理器控制台后 我收到以下消息 Error The Package Manager Console requires PowerShell 2 0 runtime
  • 使用猫鼬进行 $lookup

    我有两个集合 例如清单和任务 两个模式如下所示 清单架构如下所示 id 5b7d0f77e231b6b530b0ee5a audit checklist type Weekly id 5b7d3f33e7a57f38084efb09 aud
  • 使用 JavaScript 动态过滤 HTML 表的行

    所以我有这张表 table border 1 align center tr td Broj pu td td Naziv pu td td ID td td Naselje td td zupanija td tr tr td td tr
  • 通过填充空格将字符串居中至指定长度

    我有一个名称向量 如下所示 x lt c Marco John Jonathan 我需要通过添加前导空格和尾随空格对其进行格式化 以便名称以 10 个字符的字符串居中 gt output 1 Marco John Jonathan 我希望有
  • Django - url 的动态视图

    我想根据 url 加载特定视图 例如 url r channel P
  • 如何调用与成员函数同名的内联友元函数?

    如此处所述C 11 风格的 SFINAE 和模板实例化上的函数可见性类成员函数掩盖了自由函数 使用完全限定名称通常是有效的 但是我在使用内联声明的其他类的友元函数时遇到了困难 考虑以下示例 namespace N struct C frie
  • 在 python 中追加到文件后没有 EOL

    我尝试使用以下代码使用 python 附加到文件 with open test txt a as myfile myfile write appended text 问题是 当我用 vim 打开文件时 我在底部收到来自 vim 的消息 te
  • 在 C 中使用 void* 指针的缺点

    使用起来有很多缺点void 在C中 内存相关 类型相关 效率方面 尽管如此 我们还是经常使用它们 因为它们提供了灵活性 列出使用的缺点 缺点void 以及 C 中的首选解决方案 如果可能 EDIT 请访问以下链接 http attracti
  • IIS FTP 是否包含用于检测文件上传何时完成的 API?

    我想使用 IIS FTP 服务器 但我需要能够判断特定用户的文件上传何时完成 我不想依赖于直接在 Windows 中监视文件更改 因为我认为我无法判断文件上传是否真正完成或已中止并且可能稍后完成 您可以使用自定义日志记录提供程序来执行此操作
  • 循环浏览网页并复制数据

    我为一位朋友创建了这个脚本 该脚本循环浏览一个房地产网站并为她获取电子邮件地址 用于促销 该网站免费提供它们 但一次获取一个很不方便 第一个脚本将每个页面的数据转储到名为 webdump 的 txt 文件中 第二个脚本从第一个 txt 文件
  • 如何使用yaml在doctrine2中模拟继承?

    如何以yaml方式声明doctrine2继承 我在学说文档中没有找到任何与此相关的代码片段 示例或食谱文章 当我尝试以doctrine1方式进行操作时 我收到一个错误 指出该实体没有主键 Thanks 尝试使用以下方法进行简单的模型继承ex
  • NVIDIA Fermi 中的 L2 缓存

    在查看NVIDIA Fermi架构中的性能计数器名称 cuda的doc文件夹中的Compute profiler txt文件 时 我注意到对于L2缓存未命中 有两个性能计数器 l2 subp0 read sector misses和l2 s
  • 获取IP地址

    In C IPHostEntry IPHost Dns GetHostEntry Dns GetHostName for int i 0 i lt IPHost AddressList Length i textBox1 AppendTex
  • 文件锁释放时收到通知

    使用C 和Windows作为平台 我有一台相机 可以将 JPG 文件写入电脑的本地文件夹中 我想加载相机丢弃的每个文件 因此我有一个 FileSystemWatcher 它会在创建新图片时通知我 但相机在写入文件时锁定文件 所以如果我在收到
  • Android,蓝牙配对后仅通过身份验证交换信息 //

    我想通过蓝牙与仅通过身份验证配对的 2 个 Android 设备交换一些信息 我已经在 Android 开发人员端看到了 Android 聊天示例示例 它运行良好 但现在我想要在 2 个设备的蓝牙配对后 想要相互交换一些信息 就像当设备将其