android蓝牙实现简单的聊天的功能

蓝牙打开的两种方式:一种是有对话框弹出,另一种是没有对话框。

          通過意图打开
               Intent open = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                //只是打開時間,单位秒
                open.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
                startActivity(open);
          //静默打开 (没有对话框)
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                adapter.enable();

关闭蓝牙

// 关闭蓝牙
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                adapter.disable();

扫描蓝牙设备:扫描的有两种结果一种是已经配对过的,另外一种就是周围有的设备

    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                adapter.startDiscovery();//开始扫描蓝牙设备
    //返回已经配对过的设备
                Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();

扫描周围的设备需要注册广播,在oncreate方法里

//注册找到设备广播
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
        registerReceiver(mReceiver, filter);  
        //注册完成扫描广播
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
        registerReceiver(mReceiver, filter);
//回掉广播
    BroadcastReceiver mReceiver = new BroadcastReceiver() {  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            //找到设备  
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {  
                BluetoothDevice device = intent  
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
      
               // if (device.getBondState() != BluetoothDevice.BOND_BONDED) {  
      
                Log.d("mytag",device.getName());
                Bean bean = new Bean();
                bean.setAddress(device.getAddress());
                bean.setName(device.getName());
                list.add(bean);
                Myadapter.notifyDataSetChanged();
               
                //}  
            }  
            //搜索完成  
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED  
                    .equals(action)) {  
                setTitle("搜索完成");  
//                if (mNewDevicesAdapter.getCount() == 0) {  
//                    Log.v("tag", "find over");  
//                }  
            }  
        }  
    };  

然后是让一个手机作为服务器,得分为以下步骤,

这里需要注意的是需要一个唯一的uuid,两端必须保持一致

1,开启子线程等待客户端接入,

2,接入成功开启接收聊天的子线程,

3,发送时开启发送子线程

package com.example.bluetooth;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.util.UUID;

import android.support.v7.app.ActionBarActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ServerActivity extends ActionBarActivity {
    private TextView tv;
    private Button send;
    private EditText input;

    private BluetoothAdapter adapter; // 蓝牙适配器
    private BluetoothServerSocket serverSocket; // 服务器socket
    private BluetoothSocket socker; // 客户端socket

    PrintStream out;
    BufferedReader in;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server);
        tv = (TextView) findViewById(R.id.sstate);
        send = (Button) findViewById(R.id.ssend);
        input = (EditText) findViewById(R.id.sinput);
        //发送按钮
        send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    
                    @Override
                    public void run() {
                        out.println(input.getText().toString());
                        out.flush();
                        handle.sendEmptyMessage(2);
                        
                    }
                }).start();
            }
        });
        init();
    }

    // 创建蓝牙服务器端
    private void init() {
        tv.setText("服务器已经启动,正在等待链接。。。\n");
        new Thread(new Runnable() {

            @Override
            public void run() {
                // 获得适配器
                adapter = BluetoothAdapter.getDefaultAdapter();

                try {
                    //uuid作为链接标识
                    serverSocket = adapter.listenUsingRfcommWithServiceRecord(
                            "test", UUID.fromString("3F2504E0-4F89-11D3-9A0C-0305E82C3301"));
                    //等待客户端连接
                    socker = serverSocket.accept();
                    if(socker!=null){
                        //获得输入输出流,向客户端输入输出信息
                        in = new BufferedReader(new InputStreamReader(socker.getInputStream()));
                        out = new PrintStream(socker.getOutputStream());
                    }
                    handle.sendEmptyMessage(0);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }).start();
    }
    private Handler handle = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            //成功
            case 0:
                tv.append("链接成功\n");
                new Thread(new ReadInfoThread()).start();
                break;
            case 1:
                String m = (String) msg.obj;
                tv.append(m+"\n");
                break;
            case 2:
                input.setText("");
                break;

            default:
                break;
            }
        };
    };
//    boolean isTrue = true;
    class ReadInfoThread implements Runnable{
        String info = "";
        @Override
        public void run() {
            while (true) {
                try {
                    info = in.readLine();
                    Message msg = handle.obtainMessage();
                    msg.what = 1;
                    msg.obj = info;
                    handle.sendMessage(msg);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }
        
    }
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        try {
            if(socker!=null)
            socker.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

客户端和服务器差不多的逻辑

package com.example.bluetooth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.UUID;

import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ClitenActivity extends ActionBarActivity {
    private TextView tv;
    private Button send;
    private EditText input;

    private BluetoothAdapter adapter; // 蓝牙适配器
    private BluetoothDevice device;
    private BluetoothSocket socker; // 客户端socket

    PrintStream out;
    BufferedReader in;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cliten);
        initView();
        init();
    }

    private void init() {
        tv.setText("正在与服务器进行连接...\n");
        new Thread(new Runnable() {

            @SuppressLint("NewApi")
            @Override
            public void run() {
                try {
                    adapter = BluetoothAdapter.getDefaultAdapter();
                    device = adapter.getRemoteDevice(getIntent().getStringExtra(
                            "address"));
                    socker = device.createInsecureRfcommSocketToServiceRecord(UUID
                            .fromString("3F2504E0-4F89-11D3-9A0C-0305E82C3301"));
                    if(socker!=null){
                        socker.connect();    
                        //获得输入输出流,想客户端输入输出信息
                        in = new BufferedReader(new InputStreamReader(socker.getInputStream()));
                        out = new PrintStream(socker.getOutputStream());
                    }
                    handle.sendEmptyMessage(0);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }).start();

    }

    private void initView() {
        tv = (TextView) findViewById(R.id.state);
        send = (Button) findViewById(R.id.send);
        input = (EditText) findViewById(R.id.input);
        send.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        out.println(input.getText().toString());
                        out.flush();
                        handle.sendEmptyMessage(2);
                    }
                }).start();
            
                
            }
        });
    }
    private Handler handle = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case 0:
                tv.append("链接成功");
                new Thread(new Runnable() {
                    String info = "";
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                info = in.readLine();
                                System.out.println("收到"+info);
                                Message msg = handle.obtainMessage();
                                msg.what = 1;
                                msg.obj = info;
                                handle.sendMessage(msg);
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        
                    }
                }).start();
                break;
            case 1:
                String m = (String) msg.obj;
                tv.append(m+"\n");
                break;
            case 2:
                input.setText("");
                break;

            default:
                break;
            }
        };
    };
    
    class ReadInfoThread implements Runnable{
        String info = "";
        @Override
        public void run() {
            while (true) {
                try {
                    info = in.readLine();
                    System.out.println("收到"+info);
                    Message msg = handle.obtainMessage();
                    msg.what = 1;
                    msg.obj = info;
                    handle.sendMessage(msg);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }
        
    }
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        try {
            if(socker!=null)
            socker.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

主界面逻辑代码

package com.example.bluetooth;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MainActivity extends ActionBarActivity {
    private List<Bean> list = new ArrayList<Bean>();
    private ListView lv;
    private MyAdapter Myadapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //注册找到设备广播
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
        registerReceiver(mReceiver, filter);  
        //注册完成扫描广播
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
        registerReceiver(mReceiver, filter);
        
        lv = (ListView) findViewById(R.id.lv);
        Myadapter = new MyAdapter(this, list);
        lv.setAdapter(Myadapter);
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Intent intent = new Intent(MainActivity.this,ClitenActivity.class);
                intent.putExtra("address",list.get(position).getAddress());
                startActivity(intent);
            }
        });
        findViewById(R.id.button4).setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,ServerActivity.class);
                startActivity(intent);
                
            }
        });
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                //打開
            /*    
             * 通過意图打开
             * Intent open = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                //只是打開時間
                open.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
                startActivity(open);*/
                
                //静默打开 (没有对话框)
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                adapter.enable();
            }
        });
        findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // 关闭蓝牙
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                adapter.disable();
                
            }
        });
        findViewById(R.id.button3).setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                adapter.startDiscovery();//开始扫描蓝牙设备
                Bean bean;
                //返回已经配对过的设备
                Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
                for (BluetoothDevice bluetoothDevice : bondedDevices) {
                    bean = new Bean();
                    bean.setName("已经配对"+bluetoothDevice.getName());
                    bean.setAddress(bluetoothDevice.getAddress());
                    list.add(bean);
                }
                Myadapter.notifyDataSetChanged();
            
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    };
    //回掉广播
    BroadcastReceiver mReceiver = new BroadcastReceiver() {  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            //找到设备  
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {  
                BluetoothDevice device = intent  
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
      
               // if (device.getBondState() != BluetoothDevice.BOND_BONDED) {  
      
                Log.d("mytag",device.getName());
                Bean bean = new Bean();
                bean.setAddress(device.getAddress());
                bean.setName(device.getName());
                list.add(bean);
                Myadapter.notifyDataSetChanged();
               
                //}  
            }  
            //搜索完成  
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED  
                    .equals(action)) {  
                setTitle("搜索完成");  
//                if (mNewDevicesAdapter.getCount() == 0) {  
//                    Log.v("tag", "find over");  
//                }  
            }  
        }  
    };  
}

 

posted @ 2016-04-19 16:46  aaddrrooiidd  阅读(369)  评论(0编辑  收藏  举报