Android 蓝牙2.0的连接通讯

1.需要的权限

<uses-feature
        android:name="android.hardware.bluetooth_le"
        android:required="true" />

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


2.
package myapplication.com.myapplicationble;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter BA;
    BluetoothServerSocket mmServerSocket;

    private static String address = "20:16:09:26:81:80"; // <==应填写蓝牙串口模块的蓝牙地址。
    private BluetoothSocket btSocket = null;
    private OutputStream outStream = null;
    public InputStream inStream = null;
    EditText editText;
    TextView textView;
    Button button, button1;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

    }
    /**
     * 连接蓝牙
     * **/
    public void connect() {
        BA = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device = BA.getRemoteDevice(address);

//          pairedDevices = BA.getBondedDevices();
        try {
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
           // new  ReceiveDatas(btSocket).start();
        } catch (IOException e) {
        }
        BA.cancelDiscovery();
        try {
            btSocket.connect();
         //   String s="sm";
            outStream = btSocket.getOutputStream();
          //  outStream.write(s.getBytes());
            //outStream.write(0x41);

            inStream = btSocket.getInputStream();
            while (true){
                byte[] buffer = new byte[100];
                int count = inStream.read(buffer);
               int a= inStream.available();
                String ss= new String(buffer, 0, count, "utf-8");
                System.out.println("***A"+ss);
      // 输出信息缺少……不全,占时不会
            }



        } catch (IOException e) {
        }
        try {
          //  btSocket.close();
        } catch (Exception e2) {

            // Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
        }
    }

    public void initView() {


        editText = (EditText) findViewById(R.id.edit);
        textView = (TextView) findViewById(R.id.textView);
        button = (Button) findViewById(R.id.button);
        button1 = (Button) findViewById(R.id.button1);
        BA = BluetoothAdapter.getDefaultAdapter();
       /**
        * 连接蓝牙
        * */
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("***11");
                as();
            }
        });
        /**
         * 发送信息
         * **/
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = editText.getText().toString();
                try {

          //   outStream.write(s.getBytes()); 发送数据

                    outStream = btSocket.getOutputStream();
                    inStream=btSocket.getInputStream();
                    outStream.write("sm".getBytes());
                    outStream.write("\r\n".getBytes());


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


    }



/**
 *
 *   连接蓝牙
 * **/
    public void as() {
        new AsyncTask() {

            @Override
            protected String doInBackground(Object[] params) {

                connect();
                return null;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
                Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }


}


-----------

3.修改 接受数据线程

private class ConnectedThread extends Thread {
       private final BluetoothSocket socket;
       private final InputStream inputStream;
       private final OutputStream outputStream;
       public ConnectedThread(BluetoothSocket socket) {
           this.socket = socket;
           InputStream input = null;
           OutputStream output = null;
           try {
               input = socket.getInputStream();
               output = socket.getOutputStream();
           } catch (IOException e) {
               e.printStackTrace();
           }
           this.inputStream = input;
           this.outputStream = output;
       }
       public void run() {
           byte[] buff = new byte[1024];
           int bytes;
           while (true) {
               try {
                   bytes = inputStream.read(buff);
                   String str = new String(buff, "ISO-8859-1");
                   str = str.substring(0, bytes);
                   Log.e("recv", str);

                   Message message=handler.obtainMessage();
                   message.obj=str;
                   handler.sendMessage(message);
               } catch (IOException e) {
                   e.printStackTrace();
                   break;
               }
           }
       }
       public void write(byte[] bytes) {
           try {
               outputStream.write(bytes);
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       public void cancel() {
           try {
               socket.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }

4.代码修改完成

package myapplication.com.myapplicationble;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter BA;
    BluetoothServerSocket mmServerSocket;
    String message="";
    private static String address = "20:16:09:26:81:80"; // <==应填写蓝牙串口模块的蓝牙地址。
    private BluetoothSocket btSocket = null;
    private OutputStream outStream = null;
    public InputStream inStream = null;
    EditText editText;
    TextView textView;
    Button button, button1;
    boolean BluetoothFlag;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

    }

    /**
     * 连接蓝牙
     **/
    public void connect() {
        BA = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device = BA.getRemoteDevice(address);

//          pairedDevices = BA.getBondedDevices();
        try {
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
        }
        BA.cancelDiscovery();
        try {
            btSocket.connect();
           // String s="sm";
            outStream = btSocket.getOutputStream();
            //outStream.write(s.getBytes());
            //outStream.write(0x41);
            inStream = btSocket.getInputStream();
//            while (true){
//                byte[] buffer = new byte[1];
//                int length = 0;
//                byte bb = 0;
//                String line = null;
//                ArrayList<Byte> list = new ArrayList<Byte>();
//                while (inStream.read(buffer) == -1) {
//                    try {
//                        Thread.sleep(100);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    System.out.print("-->"   +inStream.read(buffer));
//                }
//            }




            /***
             * 1
             * **/
//            while (true) {
//
//                if(inStream.available()>=0){
//                    byte[] buffer = new byte[1024];
//                    int count = inStream.read(buffer);
//                    // System.out.println("***MAX:" + a);
//                    String ss = new String(buffer, 0, count, "utf-8");
//                    System.out.println("*--" + ss);
//                }
//
//            }




            /****
             *  2
             * */

//            BluetoothFlag = true;
//            MyThread bluetoothThread = new MyThread();
//            bluetoothThread.start();

            /***
             *
             *  3
             *  */

            ConnectedThread connectedThread = new ConnectedThread(btSocket);
            connectedThread.start();

        } catch (IOException e) {
        }
        try {
            //  btSocket.close();
        } catch (Exception e2) {

            // Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
        }
    }

    public void initView() {


        editText = (EditText) findViewById(R.id.edit);
        textView = (TextView) findViewById(R.id.textView);
        button = (Button) findViewById(R.id.button);
        button1 = (Button) findViewById(R.id.button1);
        BA = BluetoothAdapter.getDefaultAdapter();
        /**
         * 连接蓝牙
         * */
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("***11");
                as();
            }
        });
        /**
         * 发送信息
         * **/
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = editText.getText().toString();
                try {

                    outStream = btSocket.getOutputStream();
                    inStream = btSocket.getInputStream();
                   // outStream.write("\r\n".getBytes());
                   outStream.write("sm".getBytes());
                  outStream.write("\r\n".getBytes());


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


    }


    /**
     * 连接蓝牙
     **/
    public void as() {
        new AsyncTask() {

            @Override
            protected String doInBackground(Object[] params) {

                connect();
                return null;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
                Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }


   /**
    * 在接受不到数据
    * **/

   private class ConnectedThread extends Thread {
       private final BluetoothSocket socket;
       private final InputStream inputStream;
       private final OutputStream outputStream;
       public ConnectedThread(BluetoothSocket socket) {
           this.socket = socket;
           InputStream input = null;
           OutputStream output = null;
           try {
               input = socket.getInputStream();
               output = socket.getOutputStream();
           } catch (IOException e) {
               e.printStackTrace();
           }
           this.inputStream = input;
           this.outputStream = output;
       }
       public void run() {
           byte[] buff = new byte[1024];
           int bytes;
           while (true) {
               try {
                   bytes = inputStream.read(buff);
                   String str = new String(buff, "ISO-8859-1");
                   str = str.substring(0, bytes);
                   Log.e("recv", str);

                   Message message=handler.obtainMessage();
                   message.obj=str;
                   handler.sendMessage(message);
               } catch (IOException e) {
                   e.printStackTrace();
                   break;
               }
           }
       }
       public void write(byte[] bytes) {
           try {
               outputStream.write(bytes);
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       public void cancel() {
           try {
               socket.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }
    Handler  handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {

            String s= (String) msg.obj;
            message=message+s;
            if(message.contains("RTS_Mon->")){
                textView.setText(message);

            }
        }
    };


}

5.布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="myapplication.com.myapplicationble.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <EditText
        android:layout_below="@+id/textView"
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:textColor="@color/hei"
        android:layout_height="wrap_content"/>
    <Button
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/button"
        android:layout_below="@+id/edit"
        android:text="send"
        />
    <Button

        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/button1"
        android:layout_below="@+id/button"
        android:text="lianjie"
        />

</RelativeLayout>

6. 实现图





7.code:

 code:链接:http://pan.baidu.com/s/1jHAL0WI 密码:xvss



### 回答1: Android Studio 蓝牙连接通讯,是指使用Android Studio软件编写程序,实现通过蓝牙通信的功能。具体实现过程如下: 1. 添加蓝牙权限 在 AndroidManifest.xml 文件中添加蓝牙权限: ``` xml <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> ``` 2. 打开蓝牙适配器 ``` java BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // 设备不支持蓝牙功能 } else { // 如果蓝牙适配器已关闭,则打开蓝牙设备 if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, requestCode); } } ``` 3. 扫描蓝牙设备 ``` java mBluetoothAdapter.startDiscovery(); ``` 4. 连接指定蓝牙设备 ``` java public class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { BluetoothSocket tmp = null; mmDevice = device; // 获取一个蓝牙Socket连接,作为客户端 try { tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { // 异常处理 } mmSocket = tmp; } public void run() { // 取消扫描蓝牙设备 mBluetoothAdapter.cancelDiscovery(); try { // 连接蓝牙设备 mmSocket.connect(); } catch (IOException connectException) { // 连接失败,关闭Socket try { mmSocket.close(); } catch (IOException closeException) { //异常处理 } return; } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { // 异常处理 } } } ``` 5. 传输数据 ``` java public class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try { // 获取输入输出流 tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { // 异常处理 } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { byte[] buffer = new byte[1024]; int bytes; while (true) { try { bytes = mmInStream.read(buffer); // 处理接收到的数据 } catch (IOException e) { // 异常处理 break; } } } public void write(byte[] bytes) { try { mmOutStream.write(bytes); } catch (IOException e) { // 异常处理 } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { // 异常处理 } } } ``` 通过以上步骤,就可以在Android Studio中实现蓝牙连接通讯的功能。 ### 回答2: AndroidStudio是一种常用的Android应用程序开发工具。它提供了一种方便、快捷、高效的方式,让开发者可以快速地创建各种类型的Android应用程序。其中,蓝牙连接通讯AndroidStudio一个非常重要的功能之一。 蓝牙连接通讯AndroidStudio的一个模块,它主要用于与其他蓝牙设备进行通讯。在使用蓝牙模块之前,您需要在Device File Explorer中找到并复制一些必需的文件。随后,您需要确保您的Android设备已启用蓝牙,并且其他蓝牙设备也已启用。 在进行蓝牙连接之前,您需要创建一个BluetoothAdapter对象。BluetoothAdapter是Android提供的一个表示蓝牙适配器的类。在成功创建一个BluetoothAdapter对象之后,您可以使用BluetoothAdapter类的其他方法来搜索其他设备并连接到它们。 在建立蓝牙连接之后,您可以使用BluetoothSocket对象与其他设备进行通讯。BluetoothSocket对象是Android提供的一个表示蓝牙连接的类。您可以使用BluetoothSocket对象的输入流和输出流来读取和写入数据。 总之,通过AndroidStudio的蓝牙连接通讯模块,您可以方便地与其他蓝牙设备进行通讯,并使用BluetoothSocket对象的输入流和输出流来读取和写入数据。如果您需要实现与其他设备的蓝牙通讯,那么使用AndroidStudio的蓝牙连接通讯模块是一个非常不错的选择。 ### 回答3: 在Android Studio中,可以使用Bluetooth API来实现蓝牙连接通讯。首先,需要进行蓝牙授权和打开蓝牙适配器的操作。然后,通过搜索周围的蓝牙设备并进行配对,以建立蓝牙连接。 一旦建立了连接,就可以通过输入输出流进行数据传输。在发送数据时,需要将数据转换为字节数组,并使用输出流将字节数组写入连接。在接收数据时,需要使用输入流从连接中读取字节数组,并将其转换为需要的数据类型。 此外,为了实现稳定和可靠的蓝牙连接,可以使用多线程来分别处理输入和输出。通过子线程进行数据传输可以防止主线程被阻塞,从而提高应用程序的响应速度和效率。 总之,蓝牙连接通讯Android Studio中必不可少的功能,可以让开发者构建各种蓝牙硬件设备的应用程序,帮助用户更好地享受各种蓝牙设备带来的便利和乐趣。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值