Android学习—蓝牙

蓝牙

蓝牙是一种支持设备短距离通信的无线电技术。能在包括移动电话,PDA,无线耳机,笔记本电脑等众多设备之间进行无线信息交换。利用“蓝牙”技术,能够有效的简化移动通信终端设备之间的通信,也能够成功的简化设备与Internet之间的通信,使得数据传输变得更加迅速高效,为无线通信拓宽道路。
Android 2.0 引入蓝牙端口,开发时需要真机测试且硬件支持。

蓝牙的基本设置

 //打开蓝牙设备
    public void openBlueToothClick(View v){

        //第一种方法,打开蓝牙设备(提示对话框)
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);

        //第二种方法,打开蓝牙,静默打开
//        BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//        bluetoothAdapter.enable();

    }
    public void closeBlueToothClick(View v){
        //关闭蓝牙设备
        BluetoothAdapter bluetoothAdapter1=BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter1.disable();

    }
    public void scanClick(View v){
        //开始扫描蓝牙设备
        BluetoothAdapter bluetoothAdapter2=BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter2.startDiscovery();
        Set<BluetoothDevice> set=bluetoothAdapter2.getBondedDevices();
        for (BluetoothDevice bd : set)
        {
            System.out.println("name"+bd.getName());
            System.out.println("address"+bd.getAddress());

        }
    }
    public void serverClick(View v){
    Intent intent=new Intent(this,ServerBluetoothActivity.class);
    startActivity(intent);
    }
    public void clientClick(View v){
        Intent intent=new Intent(this,ClientBluetoothActivity.class);
        startActivity(intent);
    }
}
 BluetoothAdapter bluetooth=null;//本地蓝牙设备
    BluetoothServerSocket serverSocket=null;//蓝牙设备Socket服务端
    BluetoothSocket socket=null;//蓝牙设备Socket客户端

    //输入输出流
    PrintStream out;
    BufferedReader in;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server_bluetooth);
        setTitle("蓝牙服务端");
        textView_content= (TextView) findViewById(R.id.textView_content);
        editText_info= (EditText) findViewById(R.id.editText_info);
        button_send= (Button) findViewById(R.id.button_send);
        init();
    }
    //创建蓝牙服务器端的Socket
    private void init() {
        textView_content.setText("服务器已启动,正在等待连接...\n");
        new Thread(new Runnable() {
            @Override
            public void run() {
                //1.得到本地设备
                bluetooth=BluetoothAdapter.getDefaultAdapter();
                //2.创建蓝牙Socket服务器
                try
                {
                    serverSocket=bluetooth.listenUsingRfcommWithServiceRecord("text", UUID.fromString("00000000-2527-eef3-ffff-ffffe3160865"));
                    //3.阻塞等待Socket客户端请求
                    socket=serverSocket.accept();
                    if (socket!=null)
                    {
                        out=new PrintStream(socket.getOutputStream());
                        in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    }
                    handler.sendEmptyMessage(CONN_SUCCESS);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                    Message msg=handler.obtainMessage(CONN_FAIL,e.getLocalizedMessage());
                    handler.sendMessage(msg);
                }

            }
        }).start();

    }

    //防止内存泄漏 正确的使用方法
    private final MyHandler handler = new MyHandler(this);

    public  class MyHandler extends Handler {
        //软引用
        WeakReference<ServerBluetoothActivity> weakReference;

        public MyHandler(ServerBluetoothActivity activity) {
            weakReference = new WeakReference<ServerBluetoothActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ServerBluetoothActivity activity = weakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case RECEIVER_INFO:
                        setInfo(msg.obj.toString() + "\n");
                        break;
                    case SET_EDITTEXT_NULL:
                        editText_info.setText("");
                        break;
                    case CONN_SUCCESS:
                        setInfo("连接成功!\n");
                        button_send.setEnabled(true);
                        new Thread(new ReceiverInfoThread()).start();
                        break;
                    case CONN_FAIL:
                        setInfo("连接失败!\n");
                        setInfo(msg.obj.toString() + "\n");
                        break;
                    default:
                        break;
                }
            }
        }
    }
    private boolean isReceiver=true;
    class ReceiverInfoThread implements Runnable {
        @Override
        public void run() {
            String info=null;
            while (isReceiver)
            {
                try {
                    info=in.readLine();
                    Message msg=handler.obtainMessage(RECEIVER_INFO,info);
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void sendClick(View v)
    {
        final String content=editText_info.getText().toString();
        if (TextUtils.isEmpty(content))
        {
            Toast.makeText(ServerBluetoothActivity.this,"不能发送空消息",Toast.LENGTH_LONG).show();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                out.println(content);
                out.flush();
                handler.sendEmptyMessage(SET_EDITTEXT_NULL);
            }
        }).start();
    }
    private void setInfo(String info)
    {
        StringBuffer sb=new StringBuffer();
        sb.append(textView_content.getText());
        sb.append(info);
        textView_content.setText(sb);
    }

 BluetoothAdapter bluetooth=null;//本地蓝牙设备
    BluetoothDevice device=null;//远程蓝牙设备
    BluetoothSocket socket=null;//蓝牙设备Socket客户端

    //输入输出流
    PrintStream out;
    BufferedReader in;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client_bluetooth);
        setTitle("蓝牙客户端");
        textView_content= (TextView) findViewById(R.id.textView_content);
        editText_info= (EditText) findViewById(R.id.editText_info);
        button_send= (Button) findViewById(R.id.button_send);
        init();
    }
    //创建蓝牙客户端端的Socket
    private void init() {
        textView_content.setText("客户端已启动,正在等待连接...\n");
        new Thread(new Runnable() {
            @Override
            public void run() {
                //1.得到本地蓝牙设备的默认适配器
                bluetooth=BluetoothAdapter.getDefaultAdapter();
                //2.通过本地蓝牙设备得到远程蓝牙设备
                device=bluetooth.getRemoteDevice("22:22:4E:6E:59:86");
                //3.根据UUID创建并返回一个BoluetoothSocket
                try {
                    socket=device.createRfcommSocketToServiceRecord(UUID.fromString("00000000-2527-eef3-ffff-ffffe3160865"));
                    if (socket!=null)
                    {
                        // 连接
                        socket.connect();
                        //处理客户端输出流
                        out=new PrintStream(socket.getOutputStream());
                        in=new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    }
                    handler.sendEmptyMessage(CONN_SUCCESS);
                } catch (IOException e) {
                    e.printStackTrace();
                    Message msg=handler.obtainMessage(CONN_FAIL,e.getLocalizedMessage());
                    handler.sendMessage(msg);

                }

            }
        }).start();
    }

    //防止内存泄漏 正确的使用方法
    private final MyHandler handler = new MyHandler(this);

    public  class MyHandler extends Handler {
        //软引用
        WeakReference<ClientBluetoothActivity> weakReference;

        public MyHandler(ClientBluetoothActivity activity) {
            weakReference = new WeakReference<ClientBluetoothActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ClientBluetoothActivity activity = weakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case RECEIVER_INFO:
                        setInfo(msg.obj.toString() + "\n");
                        break;
                    case SET_EDITTEXT_NULL:
                        editText_info.setText("");
                        break;
                    case CONN_SUCCESS:
                        setInfo("连接成功!\n");
                        button_send.setEnabled(true);
                        System.out.println("name"+device.getName());
                        System.out.println("Uuids"+device.getUuids());
                        System.out.println("Address"+device.getAddress());
                        new Thread(new ReceiverInfoThread()).start();
                        break;
                    case CONN_FAIL:
                        setInfo("连接失败!\n");
                        setInfo(msg.obj.toString() + "\n");
                        break;
                    default:
                        break;
                }
            }
        }
    }


    private boolean isReceiver=true;
    //接收信息的线程
    class ReceiverInfoThread implements Runnable {
        @Override
        public void run() {
            String info=null;
            while (isReceiver)
            {
                try {
                    System.out.println("--ReceiverInfoThread start --");
                    info=in.readLine();
                    System.out.println("--ReceiverInfoThread read --");
                    Message msg=handler.obtainMessage(RECEIVER_INFO,info);
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void sendClick(View v)
    {
        final String content=editText_info.getText().toString();
        if (TextUtils.isEmpty(content))
        {
            Toast.makeText(ClientBluetoothActivity.this,"不能发送空消息",Toast.LENGTH_LONG).show();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                out.println(content);
                out.flush();
                handler.sendEmptyMessage(SET_EDITTEXT_NULL);
            }
        }).start();
    }
    private void setInfo(String info)
    {
        StringBuffer sb=new StringBuffer();
        sb.append(textView_content.getText());
        sb.append(info);
        textView_content.setText(sb);
    }
}

主界面
在这里插入图片描述

<Button
        android:id="@+id/button_open"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp"
        android:onClick="openBlueToothClick"
        android:text="打开蓝牙设备" />

    <Button
        android:id="@+id/button2_close"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button_open"
        android:layout_alignParentStart="true"
        android:layout_marginStart="0dp"
        android:onClick="closeBlueToothClick"
        android:layout_marginTop="25dp"
        android:text="关闭蓝牙设备" />

    <Button
        android:id="@+id/button3_scan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2_close"
        android:layout_alignParentStart="true"
        android:layout_marginStart="0dp"
        android:onClick="scanClick"
        android:layout_marginTop="20dp"
        android:text="搜索蓝牙设备" />

    <Button
        android:id="@+id/button4_server"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button3_scan"
        android:layout_alignParentStart="true"
        android:layout_marginStart="0dp"
        android:onClick="serverClick"
        android:layout_marginTop="18dp"
        android:text="服务器端" />

    <Button
        android:id="@+id/button5_client"
        android:layout_width="match_parent"
        android:layout_height="58dp"
        android:layout_below="@+id/button4_server"
        android:layout_alignParentStart="true"
        android:layout_marginStart="0dp"
        android:onClick="clientClick"
        android:layout_marginTop="12dp"
        android:text="客户端" />

客户端的界面设置
在这里插入图片描述

 <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text=""
        android:id="@+id/textView_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/editText_info"
        android:layout_below="@+id/textView" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText_info"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/button_send"
        android:layout_toStartOf="@+id/button_send" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send"
        android:id="@+id/button_send"
        android:onClick="sendClick"
        android:layout_alignBottom="@+id/editText_info"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="客户端"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

服务器端的界面设置

在这里插入图片描述

 <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text=""
        android:id="@+id/textView_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/editText_info"
        android:layout_below="@+id/textView" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText_info"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/button_send"
        android:layout_toStartOf="@+id/button_send" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send"
        android:id="@+id/button_send"
        android:onClick="sendClick"
        android:layout_alignBottom="@+id/editText_info"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="服务器端"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Android蓝牙完全学习手册为用户提供了关于在Android平台上使用蓝牙技术的详细指南和教程。这个手册非常详尽和全面,可以帮助用户了解蓝牙技术的基础知识以及如何在Android设备上使用蓝牙功能。 手册的内容包括以下几个主要方面: 1. 蓝牙基础知识:介绍了蓝牙技术的原理和工作方式,包括蓝牙的发展历程、蓝牙的频段和速度、蓝牙设备的分类等。 2. Android平台下的蓝牙支持:详细介绍了Android系统对蓝牙技术的支持,包括蓝牙API的使用方法、蓝牙权限的配置、蓝牙开发工具的选择等。 3. 蓝牙连接与通信:指导用户如何在Android设备上建立蓝牙连接,包括搜索周围的蓝牙设备、配对和连接设备等。同时还介绍了蓝牙通信的基本原理和实现方法,如数据传输、蓝牙协议栈等。 4. 蓝牙应用开发:教授用户如何开发自己的蓝牙应用程序,包括蓝牙文件传输、蓝牙音频传输、蓝牙打印技术等。 此外,手册还提供了一些实例代码和案例分析,帮助用户更好地理解和应用所学的知识。 总之,Android蓝牙完全学习手册是一本内容十分丰富的教程,它将帮助用户从零开始学习和掌握Android平台上的蓝牙技术,提供了全面而具体的指导,对于那些有兴趣开发蓝牙应用的Android开发者来说,是一本不可缺少的学习资料。 ### 回答2: Android蓝牙完全学习手册是一本详细介绍Android蓝牙开发的书籍。Android蓝牙作为一种无线通信技术,广泛应用于各种移动设备和智能设备之间的数据传输和连接。学习手册的目的是帮助读者深入了解Android蓝牙的原理、实现方式和应用场景。 学习手册首先介绍了Android蓝牙的基本概念和工作原理。它解释了如何通过蓝牙适配器在设备之间建立连接,并传输数据。手册详细讲解了蓝牙的不同协议和服务,例如RFCOMM、L2CAP、A2DP等。读者可以了解到每种协议的特点和适用场景。 接下来,学习手册提供了实际的代码示例,教读者如何在Android平台上进行蓝牙开发。它讲解了如何通过API调用进行设备的搜索、配对、连接和断开连接操作。手册还介绍了如何发送和接收数据,并处理连接状态和错误的情况。读者可以通过这些实例了解到如何在自己的应用程序中集成蓝牙功能。 此外,学习手册还介绍了一些进阶的蓝牙开发技巧和注意事项。它探讨了蓝牙安全性和权限管理,以及如何处理蓝牙设备的兼容性问题。手册还提供了一些性能优化的建议,帮助开发者提升应用程序的蓝牙连接速度和稳定性。 Android蓝牙完全学习手册是一本系统全面的学习资源,适合无论是初学者还是有一定经验的开发者。通过阅读学习手册,读者可以掌握Android平台上蓝牙开发的基础知识和技能,从而能够开发出功能强大、稳定可靠的蓝牙应用程序。 ### 回答3: Android蓝牙完全学习手册是一本详细介绍Android平台下蓝牙开发的教程书籍。这本手册适合已经具备一定基础知识的Android开发者学习和参考。以下是这本学习手册的主要内容: 首先,手册会从蓝牙基础知识开始介绍,包括蓝牙技术原理、蓝牙协议栈以及蓝牙通信的常用术语和概念。这部分内容旨在帮助读者全面了解蓝牙技术背后的原理和工作机制。 接着,手册会详细介绍如何在Android平台上使用蓝牙功能。它会讲解如何配置设备的蓝牙设置、如何搜索和配对其他蓝牙设备、以及如何建立蓝牙连接和进行数据传输。此外,手册还会介绍如何处理蓝牙设备间的通信协议和数据格式。 手册中还会介绍如何开发蓝牙应用程序,并提供一些常见的蓝牙应用场景的示例代码。这些示例代码可以帮助读者理解如何使用Android提供的API来实现不同类型的蓝牙应用功能,如蓝牙耳机控制、蓝牙数据传输等。 此外,手册还会讲解一些高级的蓝牙开发技术,如如何处理多个蓝牙设备的连接、如何实现蓝牙设备的自动连接和断开等。这些技术对于需要开发复杂蓝牙应用的开发者来说尤为重要。 总的来说,Android蓝牙完全学习手册是一本系统、全面讲解Android蓝牙开发知识的书籍。通过学习这本手册,读者可以掌握在Android平台上开发蓝牙应用的基本技能,并能够应对更复杂的蓝牙应用开发需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值