文档章节

蓝牙Socket通信,注意权限

22m
 22m
发布于 2016/12/28 14:56
字数 1837
阅读 84
收藏 0

服务端:

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private BluetoothAdapter btAdapter;
    private String btAdress;
    private InputStream input;
    private OutputStream output;
    private Handler handler;
    final String uuid = "af3ad9b2-0ea6-4a90-be06-a1c86bc7e28b";
    private TextView getInformationText;
    private Button one;
    private Button two;
    private Button three;
    private Button four;
    private Button five;
    private Button six;
    private int position;
    private Map<Integer, Button> map;
    public static boolean isRunning = true;
    private BroadcastReceiver receiver;
    private IntentFilter filter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        position = 1;
        //初始化
        one = (Button) findViewById(R.id.one);
        two = (Button) findViewById(R.id.two);
        three = (Button) findViewById(R.id.three);
        four = (Button) findViewById(R.id.four);
        five = (Button) findViewById(R.id.five);
        six = (Button) findViewById(R.id.six);

        two.setEnabled(false);
        three.setEnabled(false);
        four.setEnabled(false);
        five.setEnabled(false);
        six.setEnabled(false);

        one.setOnClickListener(this);
        two.setOnClickListener(this);
        three.setOnClickListener(this);
        four.setOnClickListener(this);
        five.setOnClickListener(this);
        six.setOnClickListener(this);
        //初始化标识
        map = new HashMap<>();
        map.put(1, one);
        map.put(2, two);
        map.put(3, three);
        map.put(4, four);
        map.put(5, five);
        map.put(6, six);

        //注册广播
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
                    Log.i("information", "hello i am a dialog~~~~~");
                    Intent btIntent = new Intent(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
                    intent.putExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED);
                    sendBroadcast(btIntent);
                }
            }
        };
        filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
        registerReceiver(receiver, filter);


        //class:


        getInformationText = (TextView) findViewById(R.id.tv);
        getInformationText.append("\n");
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        //打开蓝牙
        if (btAdapter.enable()) {
            Toast.makeText(this, "蓝牙已成功打开", Toast.LENGTH_LONG).show();
            btAdress = btAdapter.getAddress();
            Log.i("information", UUID.randomUUID().toString());
            //让自己的蓝牙设备永远地可以被搜索到
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
            startActivity(intent);
            new btGetConnectionThread(btAdapter).start();
        } else {
            Toast.makeText(this, "请打开蓝牙!", Toast.LENGTH_LONG).show();
        }

        //初始化handler
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                final String information = ((String) msg.obj);
                Log.i("information", information + "-----------" + isRunning);
                if (isRunning) {
                    get_And_Do(information);
                } else {
                    //发送信息到下一个界面
                    sendBroadcast(new Intent("send_to_me").putExtra("the_order", information));
                }
                //getInformationText.append("     Zzm: " + information + "\n");
            }
        };
    }


    public void click(View view) {
        Toast.makeText(this, "已开启连接!", Toast.LENGTH_LONG).show();
        new btGetConnectionThread(btAdapter).start();
    }


    //等待请求的连接
    private class btGetConnectionThread extends Thread {
        private BluetoothServerSocket btServerSocket;
        private BluetoothSocket btSocket;

        public btGetConnectionThread(BluetoothAdapter btAdapter) {
            try {
                btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord(UUID.randomUUID().toString(),
                        UUID.fromString(uuid));
                if (btServerSocket == null) {
                    Toast.makeText(MainActivity.this, "蓝牙建立连接失败!", Toast.LENGTH_LONG).show();
                    return;
                } else {
                    Toast.makeText(MainActivity.this, "蓝牙正在等待连接!", Toast.LENGTH_LONG).show();
                }
            } catch (IOException e) {
                Log.i("information", e.toString());
            }
        }

        @Override
        public void run() {
            super.run();
            //等待客户端来的连接
            try {
                btSocket = btServerSocket.accept();
            } catch (IOException e) {
                // Toast.makeText(MainActivity.this,"蓝牙连接,接收失败!",Toast.LENGTH_LONG).show();
                new btGetConnectionThread(btAdapter).start();
                return;
            }
            if (btSocket != null) {
                try {
                    // Toast.makeText(MainActivity.this,"蓝牙连接成功!",Toast.LENGTH_LONG).show();
                    btServerSocket.close();
                    try {
                        input = btSocket.getInputStream();
                        output = btSocket.getOutputStream();
                        new GetInformationThread().start();
                    } catch (IOException e) {
                        Log.i("information", "获取流失败!");
                    }
                    //连接成功后要做的事情

                } catch (IOException e) {
                    Log.i("information", e.toString());
                    //    Toast.makeText(MainActivity.this,"蓝牙连接关闭失败!正在重新等待连接!",Toast.LENGTH_LONG).show();
                    new btGetConnectionThread(btAdapter).start();
                    return;
                }
            } else {
                Log.i("information", "获取,socket失败!");
                //  Toast.makeText(MainActivity.this,"蓝牙连接失败,正在重新等待连接!",Toast.LENGTH_LONG).show();
                new btGetConnectionThread(btAdapter).start();
                //Looper.loop();
                return;
            }
        }

    }


    //连接后接收信息的线程

    private class GetInformationThread extends Thread {
        @Override
        public void run() {
            super.run();
            boolean is = true;
            while (is) {
                byte[] bytes = new byte[1024];
                int length = 0;
                String getInformation = null;
                if (input != null || output != null) {
                    try {
                        length = input.read(bytes);
                        getInformation = new String(bytes, 0, length, "utf-8");
                        //处理信息
                        Message message = new Message();
                        message.obj = getInformation;
                        handler.sendMessage(message);
                    } catch (IOException e) {
                        Log.i("information", e.toString());
                    }
                }
            }
        }
    }


    //写的监听事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.one:
                //方法:下面同上
                one();
                break;

            case R.id.two:
                two();
                break;

            case R.id.three:
                three();
                break;

            case R.id.four:
                four();
                break;

            case R.id.five:
                five();
                break;

            case R.id.six:
                six();
                break;


        }

    }

    //各个控制的方法
    private void one() {
        isRunning = false;
        startActivity(new Intent(this, One.class));
    }

    private void two() {
        startActivity(new Intent(this, Two.class));
        isRunning = false;
    }

    private void three() {
        startActivity(new Intent(this, Three.class));
        isRunning = false;
    }

    private void four() {
        startActivity(new Intent(this, Four.class));
        isRunning = false;
    }

    private void five() {
        startActivity(new Intent(this, Five.class));
        isRunning = false;
    }

    private void six() {
        startActivity(new Intent(this, Six.class));
        isRunning = false;
    }

    //得到控制端的信息再做出相应的反应
    private void get_And_Do(String information) {
        switch (information) {
            case "left":
                if (position != 1 && position != 4) {
                    map.get(position).setEnabled(false);
                    map.get(position - 1).setEnabled(true);
                    position -= 1;
                }
                break;
            case "front":
                if (position != 1 && position != 2 && position != 3) {
                    map.get(position).setEnabled(false);
                    map.get(position - 3).setEnabled(true);
                    position -= 3;
                }
                break;
            case "down":
                if (position != 4 && position != 5 && position != 6) {
                    map.get(position).setEnabled(false);
                    map.get(position + 3).setEnabled(true);
                    position += 3;
                }
                break;

            case "right":
                if (position != 6 && position != 3) {
                    map.get(position).setEnabled(false);
                    map.get(position + 1).setEnabled(true);
                    position += 1;
                }
                break;
            case "sure":
                map.get(position).callOnClick();
                break;
        }
    }


}

客户端:

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class Android_below_four_zero extends AppCompatActivity {
    private TextView textView1;
    private TextView textView2;
    private BluetoothAdapter btAdapter;
    final int STARTBLUETOOTH = 1994;
    final int SCANBLUETOOTH = 2010;
    private BluetoothSocket btSocket;
    private Handler handler1;
    private InputStream input;
    private OutputStream output;
    private BroadcastReceiver btResult;
    private BluetoothDevice btDevice;
    //UUID
    final String uuid = "af3ad9b2-0ea6-4a90-be06-a1c86bc7e28b";
    private EditText sendInformation;
    private Button sending;
    private Button front;
    private Button down;
    private Button left;
    private Button right;
    private Button sure;
    private Button back;
    private ControlOrder order;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //initialView
        textView1 = (TextView) findViewById(R.id.Bt1);
        textView2 = (TextView) findViewById(R.id.Bt2);

        front = (Button) findViewById(R.id.front);
        down = (Button) findViewById(R.id.down);
        left = (Button) findViewById(R.id.left);
        right = (Button) findViewById(R.id.right);
        sure = (Button) findViewById(R.id.sure);
        back = (Button) findViewById(R.id.back);


        sendInformation = ((EditText) findViewById(R.id.send));

        sending = ((Button) findViewById(R.id.sending));

        //获取蓝牙设备管理对象
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        //判断蓝牙是否打开,如果没有就会提醒打开
        if (btAdapter.isEnabled()) {
            Toast.makeText(this, "蓝牙已成功打开", Toast.LENGTH_SHORT).show();
            textView1.setText("本地蓝牙的名字:" + btAdapter.getName());
            //扫描设备
            bluetoothScaning(btAdapter);
        } else {
            startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), STARTBLUETOOTH);
        }


        //发现设备的广播
        btResult = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                Log.i("information", "---------" + action);
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    btDevice =intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (null == btDevice) {
                        Toast.makeText(context, "未发现设备", Toast.LENGTH_SHORT).show();
                    } else {
                        textView2.setText("扫描到的蓝牙的名字:" + btDevice.getName());
                    }
                }

                if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    Toast.makeText(context, "搜索蓝牙完成", Toast.LENGTH_SHORT).show();
                }

                if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                    int state = btDevice.getBondState();
                    if (state == BluetoothDevice.BOND_BONDED)
                        Toast.makeText(context, "完成配对", Toast.LENGTH_SHORT).show();
                    if (state == BluetoothDevice.BOND_BONDING)
                        Log.i("information","正在配对");
                    if (state == BluetoothDevice.BOND_NONE)
                        Log.i("information","配对取消");
                }

                if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
                    Toast.makeText(context, "正在请求配对!", Toast.LENGTH_SHORT).show();
                    //BluetoothaAutoConnectUtils.setPassWord(btDevice.getClass(),btDevice,"0000");
                }
            }
        };


        //注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
        registerReceiver(btResult, filter);

    }


    //打开蓝牙后返回的数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == STARTBLUETOOTH && resultCode == RESULT_OK) {
            Toast.makeText(this, "蓝牙已成功打开", Toast.LENGTH_SHORT).show();
            textView1.setText("本地蓝牙的名字:" + btAdapter.getName());
            bluetoothScaning(btAdapter);
        } else if (requestCode == SCANBLUETOOTH && resultCode == RESULT_OK) {
            /////

            //////
        } else {
            Toast.makeText(this, "蓝牙操作失败", Toast.LENGTH_LONG).show();
            Toast.makeText(this, "" + requestCode + "     " + resultCode, Toast.LENGTH_LONG).show();

        }

        //

    }


    //蓝牙扫描的方法
    private void bluetoothScaning(BluetoothAdapter btAdapter) {
        if (btAdapter.getScanMode() == BluetoothAdapter.SCAN_MODE_NONE) {
            //如果没在扫描则开启扫描
            Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            //设置扫描时间
            btIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 6000);
            startActivityForResult(btIntent, SCANBLUETOOTH);
            // Log.i("information","hello");
        } else {
            //如果在扫描,或则已经获取了结果,开启重新扫描
            if (!btAdapter.isDiscovering()) {
                btAdapter.startDiscovery();
            } else {
                //停止扫描重新扫描
                btAdapter.cancelDiscovery();
                btAdapter.startDiscovery();
            }
        }
    }

    //解除注册的广播
    @Override
    protected void onDestroy() {
        unregisterReceiver(btResult);
        btAdapter.disable();
        super.onDestroy();
    }

    //重新连接
    public void click(View view) {
        bluetoothScaning(btAdapter);
    }


    //执行连接
    public void click_1(View view) {
         new BtConnectThread(btDevice).start();
        // BluetoothaAutoConnectUtils.createConnection(btDevice.getClass(),btDevice);
    }

    //建立请求连接蓝牙的线程
    private class BtConnectThread extends Thread {
        public BtConnectThread(BluetoothDevice btDevice) {
            //获取通信Socket
            if (null != btDevice) {
                try {
                    btSocket = btDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(uuid));
                } catch (IOException e) {
                    Toast.makeText(Android_below_four_zero.this, "蓝牙建立连接失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(Android_below_four_zero.this, "蓝牙未搜索到设备", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void run() {
            super.run();
            Looper.prepare();
            if (btSocket != null) {
                try {
                    btAdapter.cancelDiscovery();
                    //连接
                    btSocket.connect();
                    if (!btSocket.isConnected()) {
                        Toast.makeText(Android_below_four_zero.this, "蓝牙连接失败,请重试", Toast.LENGTH_SHORT).show();
                    } else {
                        if (!btDevice.getName().equals("null")) {
                            Toast.makeText(Android_below_four_zero.this, "与 " + btDevice.getName() + " 蓝牙设备连接成功", Toast.LENGTH_SHORT).show();
                            try {
                                input = btSocket.getInputStream();
                                output = btSocket.getOutputStream();
                                if (null != output) {
                                    Log.i("information", "---------------------11");
                                    control();
                                }

                                if (null != input) {
                                    Log.i("information", "---------------------22");
                                }

                            } catch (IOException e) {
                                Log.i("information", "获取流失败!");

                            }
                            Looper.loop();
                        } else {
                            Toast.makeText(Android_below_four_zero.this, "蓝牙连接成功", Toast.LENGTH_SHORT).show();
                            try {
                                input = btSocket.getInputStream();
                                output = btSocket.getOutputStream();
                                control();
                            } catch (IOException e) {
                                Log.i("information", "获取流失败!");
                            }
                            Looper.loop();
                        }

                        //连接成功时候的操作

                    }
                } catch (Exception e) {
                    Toast.makeText(Android_below_four_zero.this, "蓝牙连接超时,请重试", Toast.LENGTH_SHORT).show();
                    Log.i("information", e.toString());
                    Looper.loop();
                }
            }
        }
    }

    //链接后的处理线程
    private class BtConnect extends Thread {
        @Override
        public void run() {
            super.run();
        }
    }

    //链接后发送信息
    public void click_2(View view) {
        if (null == output || null == input) {
            Toast.makeText(Android_below_four_zero.this, "蓝牙连接异常!不能发信息", Toast.LENGTH_SHORT).show();
        } else {
            String information = sendInformation.getText().toString();
            if (TextUtils.isEmpty(information)) {
                Toast.makeText(Android_below_four_zero.this, "不能发送空信息!", Toast.LENGTH_LONG).show();
            } else {
                //发送信息
                byte[] bytes = new byte[0];
                try {
                    bytes = information.getBytes("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                try {
                    output.write(bytes);
                    Log.i("information", information);
                    Toast.makeText(Android_below_four_zero.this, "发送信息成功!", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    Toast.makeText(Android_below_four_zero.this, "发送信息失败!", Toast.LENGTH_LONG).show();
                }
            }

        }
        sendInformation.setText("");
    }

    //初始化监听器以及监听
    private void control() {
        order = new ControlOrder(this, output, R.id.front,
                R.id.down,
                R.id.left,
                R.id.right,
                R.id.sure,
                R.id.back);
        //设置指令监听
        front.setOnClickListener(order);
        down.setOnClickListener(order);
        left.setOnClickListener(order);
        right.setOnClickListener(order);
        sure.setOnClickListener(order);
        back.setOnClickListener(order);
    }

}

© 著作权归作者所有

22m

22m

粉丝 0
博文 40
码字总数 49283
作品 0
成都
程序员
私信 提问
Android蓝牙开发的一点总结

蓝牙的开发和使用中,主要过程为: (1)本机蓝牙设备的开启 (2)扫描周边可用蓝牙设别 (3)配对设备 (4)连接设备创建RFCOMM信道进行数据通信 1.添加权限 在android开发之前需要添加Blu...

Vincent540329
2015/07/04
889
0
Android 蓝牙开发(一)蓝牙通信

1 蓝牙基本操作 随着可穿戴设备的流行,研究蓝牙是必不可少的一门技术了。 总结了下蓝牙开发使用的一些东西分享一下。 蓝牙权限首先需要AndroidManifest.xml文件中添加操作蓝牙的权限。 允许...

VNanyesheshou
2016/06/07
0
0
Android蓝牙开发—经典蓝牙详细开发流程

Android蓝牙开发前,首先要区分是经典蓝牙开发还是BLE(低功耗)蓝牙开发,它们的开发是有区别的,如果还分不清经典蓝牙和BLE(低功耗)蓝牙的小伙伴,可以先看Android蓝牙开发—经典蓝牙和B...

天王盖地虎626
01/08
106
0
Android Bluetooth 学习(2)应用层实现蓝牙设备查找、tcp_ip通信

Bluetooth结构 1、JAVA层 frameworks/base/core/java/android/bluetooth/ 包含了bluetooth的JAVA类。 2、JNI层 frameworks/base/core/jni/androidbluetooth开头的文件 定义了bluez通过JNI到上......

zhoulc
2013/03/18
6.5K
0
Android蓝牙开发技术指南

Android蓝牙开发技术指南 Android 蓝牙开发技术 要学习蓝牙先认识 一 RFCOMM 通道: RFCOMM 协议 一个基于欧洲电信标准协会 ETSI07.10 规程的串行线性仿真协议。此协议提供 RS232 控制和状态...

庸人谷
2012/12/06
1K
0

没有更多内容

加载失败,请刷新页面

加载更多

安全组和云防火墙的区别

前言 熟悉云平台的朋友可能都会注意到这样一个事情:无论公有云还是私有云,创建虚拟机的时候都需要选择安全组,来对虚拟机进行安全防护;有的云平台在VPC里,还能选择防火墙,ZStack在3.6版...

ZStack社区版
21分钟前
2
0
教育性app开发的重要性和好处

在这个精通技术的世界中,流行的app主导着无聊的教育系统。当我们将技术和教育结合在一起时,它将带来当代以及强大的学习资源。因此,将教育移动app集成到您的学习过程中,并根据自己的信念把...

a429011717
22分钟前
3
0
IE6/7/8如何兼容CSS3属性

本文转载于:专业的前端网站➩IE6/7/8如何兼容CSS3属性 最近在工作中总是要求IE8兼容CSS3属性,在网上搜了搜主要是引入了一个htc文件(ie-css3.htc或者PIE.htc。个人认为这两个文件的作用差不...

前端老手
37分钟前
3
0
手把手教你ALLEGRO的约束规则的设置教程!

约束规则的设置 分三步, 定义规则(一、基本约束规则设置:1、线间距设置;2、线宽设置;3、设置过孔;4、区域约束规则设置;5、设置阻抗;6、设置走线的长度范围;7、设置等长:7.1、不过电阻的NET 等...

demyar
39分钟前
4
0
完美解决H5滚动滑动穿透方案:不使用系统滚动

网上有很多黑科技解决这个问题,都不是从根本去解决,例如通过js控制弹出时html加上position:fixed; 弹窗关闭后再去掉该样式,总觉得不太对,像是打补丁。 今天终于找到了滚动穿透的原因和完...

未来cc
43分钟前
6
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部