安卓蓝牙通信

package syd.myapplicationbluetooth;
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.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private BluetoothAdapter bluetoothAdapter;
    private ListView listview;
    private List<String> stringList=new ArrayList<>();
    private ArrayAdapter<String> arrayAdapter;
    private UUID MYUUID=UUID.fromString("550E8400-E29B-11D4-A716-446655440000");//8-4-4-4-12,十六进制
    private BluetoothServerSocket bluetoothServerSocket;
    private BluetoothSocket bluetoothSocket;
    private OutputStream os;
    private InputStream is;
    private final String NAME = "Bluetooth_Socket";
    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listview= (ListView) findViewById(R.id.listview);
        editText= (EditText) findViewById(R.id.edtext);
        arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stringList);
        listview.setAdapter(arrayAdapter);
        listview.setOnItemClickListener(this);
        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
    //每一个设备被找到,每找到一个设备会发送一次广播
    IntentFilter intentFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
   //注册接收器
    this.registerReceiver(myreceive,intentFilter);
    //搜索完毕后发送广播
    IntentFilter intentFilter1=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    this.registerReceiver(myreceive,intentFilter1);
        //获取之前配过对的蓝牙
        Set<BluetoothDevice> bluetoothdevice=bluetoothAdapter.getBondedDevices();
        System.out.println(bluetoothdevice.size());
        if (bluetoothdevice.size()>0){
            for (BluetoothDevice bounddevice:bluetoothdevice
                    ) {
                String ds=bounddevice.getName() + ":" + bounddevice.getAddress();
                System.out.println(ds);
                stringList.add(ds);
            }
        }
        findViewById(R.id.btnopenbluetooth).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             /*   Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent,1);*/
              /*  BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (!bluetoothAdapter.isEnabled())
                    bluetoothAdapter.enable();*/
//                bluetoothAdapter.disable();searchBlueTooth
                searchBlueTooth();
            }
        });
        try {
            AcceptThread acceptThread=new AcceptThread();
            acceptThread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        findViewById(R.id.btnsend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (os!=null){
                    try {
                        os.write(editText.getText().toString().getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }
private void searchBlueTooth() {
    //搜索方法不能调用两次
    // TODO: 2015/10/17
 /* setProgressBarIndeterminateVisibility(true);
    setProgressBarIndeterminate(true);*/
    setTitle("正在搜索.....");
    if (bluetoothAdapter.isDiscovering()){
        System.out.println("______________________");
        bluetoothAdapter.cancelDiscovery();
    }
    bluetoothAdapter.startDiscovery();//此语句是异步的,执行后会立即执行后面的语句

    }
    private final BroadcastReceiver myreceive=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()){
                case BluetoothDevice.ACTION_FOUND://搜到一个已绑定的蓝牙
                    System.out.println("================");
                    BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (device.getBondState()!=BluetoothDevice.BOND_BONDED){
                        stringList.add(device.getName()+":"+device.getAddress());
                    }
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED://搜索完毕
                   /* setProgressBarIndeterminate(false);
                    setProgressBarIndeterminateVisibility(false);*/
                    setTitle("已经搜索完成");
                    break;
            }

        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String s=stringList.get(position);
        //获取地址,相当于网络的ip
        String address=s.substring(s.indexOf(":")+1).trim();//吧空格戒掉
        BluetoothDevice device=bluetoothAdapter.getRemoteDevice(address);
        if (bluetoothAdapter.isDiscovering()){
            bluetoothAdapter.cancelDiscovery();
        }
        if (device!=null){
            try {
                bluetoothSocket=device.createRfcommSocketToServiceRecord(MYUUID);
                bluetoothSocket.connect();
                os=bluetoothSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String message=msg.obj.toString();
            Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
            Toast.makeText(MainActivity.this,"djh",Toast.LENGTH_LONG).show();

        }
    };
    private class AcceptThread extends Thread{
        private BluetoothServerSocket bluetoothServerSocket01;
        private BluetoothSocket bluetoothSocket01;
        public AcceptThread() throws IOException {
            bluetoothServerSocket01=bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME,MYUUID);
        }

        @Override
        public void run() {
            try {
                bluetoothSocket01=bluetoothServerSocket01.accept();
                is=bluetoothSocket01.getInputStream();
                os=bluetoothSocket01.getOutputStream();
                while (true){

                    byte[]bytes=new byte[1024];
                    int count=is.read(bytes);
                    Message message=new Message();
                    message.obj=new String(bytes,0,count,"UTF-8");
                    if (count!=0)
                    handler.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();

            }

        }
    }

}

//权限

 <uses-permission android:name="android.permission.BLUETOOTH"/>
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<!-- <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>-->
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

春哥一号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值