蓝牙Socket通信,注意权限

服务端:

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);
    }

}

转载于:https://my.oschina.net/u/2987490/blog/813761

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值