关闭

Android 蓝牙传输数据

标签: android蓝牙
629人阅读 评论(0) 收藏 举报
分类:

Android 蓝牙传输数据.

一个简单的从一个手机传输数据到另外的一个手机里面.如果要传输文件的,可以自己增加文件读写功能.

demo下载:http://download.csdn.net/detail/weijiqian/9535393
参考:
http://blog.csdn.net/q610098308/article/details/45248423
http://blog.csdn.net/qinjuning/article/details/7726093
所有代码都在MainActivity里面,附代码如下:



import android.app.Activity;
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.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

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

public class MainActivity extends Activity implements AdapterView.OnItemClickListener {

    Button open;
    Button close;
    Button listBtn;
    ListView listview;
    Button  search;

    /**
     * 设备列表
     */
    ArrayList deviceList;

    ArrayAdapter adapter;
    /**
     * //已经配对的设备
     */
    Set<BluetoothDevice> deviceSet;

    /**
     * 蓝牙适配器
     */
    BluetoothAdapter bluetoothAdapter;

    /**
     * UUID,是随便写的,两个配对的设备UUID要是一样的.
     */
    private final UUID MY_UUID = UUID.fromString("e220ff28-b64a-4cbc-804b-a73dfcdc3941");

    private final String NAME = "bluetoothSocket";

    /**
     * 蓝牙客户端
     */
    private BluetoothSocket clientSocket;

    /**
     * 蓝牙设备
     */
    private BluetoothDevice device;

    /**
     * 输出流
     */
    private OutputStream ous;

    /**
     * 线程,接受传递过来的数据.
     */
    private AcceptThread acceptThread ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        open = (Button) findViewById(R.id.open);
        close = (Button) findViewById(R.id.close);
        listBtn = (Button) findViewById(R.id.show_list);
        search = (Button) findViewById(R.id.search);
        listview = (ListView) findViewById(R.id.list_view);

        //实例化蓝牙
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        //初始化蓝牙列表显示.
        deviceList = new ArrayList();
        adapter = new ArrayAdapter
                (this,android.R.layout.simple_list_item_1, deviceList);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(this);

        //注册广播,接受扫描附近蓝牙的结果.
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filter);

        //开启线程.监听数据.
        acceptThread = new AcceptThread();
        acceptThread.start();

        open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openBluetooth();
            }

        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchBluetooth();
            }


        });


        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    closeBluetooth();
            }
        });

        listBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showList();
            }
        });


    }




    private void openBluetooth() {
        //打开蓝牙
        if(!bluetoothAdapter.isEnabled()){
            //弹出对话框提示用户是后打开
            Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enabler, 0);
            Toast.makeText(MainActivity.this,"打开蓝牙",Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(MainActivity.this,"蓝牙已经打开",Toast.LENGTH_LONG).show();
        }

        //打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)
         Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒)
        startActivityForResult(discoveryIntent,0);
    }


    private void searchBluetooth() {
        if ( !bluetoothAdapter.isDiscovering()){
            deviceList.clear();
            bluetoothAdapter.startDiscovery();
            Toast.makeText(MainActivity.this,"蓝牙开始扫描",Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(MainActivity.this,"蓝牙正在扫描",Toast.LENGTH_LONG).show();
        }

    }

    private void showList() {
        //已经配对的设备
        deviceSet = bluetoothAdapter.getBondedDevices();
        deviceList.clear();

        for(BluetoothDevice bt : deviceSet)
            deviceList.add(bt.getName() +":"+bt.getAddress());

        adapter.notifyDataSetChanged();
    }

    private void closeBluetooth() {
        if (bluetoothAdapter.isEnabled()){
            bluetoothAdapter.disable();
        }

    }


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

                Toast.makeText(MainActivity.this,"搜索到设备",Toast.LENGTH_LONG).show();
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {

                    Log.e("dddd", "find device:" + device.getName()
                            + device.getAddress());
                    deviceList.add(device.getName()+":"+ device.getAddress());
                    adapter.notifyDataSetChanged();
                }
            }
            //搜索完成
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                Toast.makeText(MainActivity.this,"搜索完成",Toast.LENGTH_LONG).show();

            }
        }
    };


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //点击配对.
        //客户端
        String s =(String) adapter.getItem(position);
        String address = s.substring(s.indexOf(":")+1).trim();

        try{
            Log.e("ddd","开始配对");
            if (bluetoothAdapter.isDiscovering()){
                bluetoothAdapter.cancelDiscovery();
            }
            if (device == null ){
                device = bluetoothAdapter.getRemoteDevice(address);
            }
            if (clientSocket ==  null ){
                clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                clientSocket.connect();

            }
            //得到输出流
            ous = clientSocket.getOutputStream();

            //把数据放到输出流.
            if (ous != null ){
                ous.write("发送数据到另外一个手机".getBytes("utf-8"));
            }

        }catch (Exception e){
            Log.e("ddd","连接出错:"+e.getMessage());
        }
    }


    //服务端
    private Handler handle = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Log.e("ddd","接受到数据");
            Toast.makeText(MainActivity.this,String.valueOf(msg.obj),Toast.LENGTH_SHORT).show();
            super.handleMessage(msg);
        }
    };


    private class  AcceptThread extends  Thread{
        private BluetoothSocket socket;
        private BluetoothServerSocket serverSocket;

        private InputStream is;
        private OutputStream os;

        private AcceptThread (){
            try{
                serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME,MY_UUID);
            }catch (Exception e){

            }

        }

        public  void run(){
            try{
                socket = serverSocket.accept();
                is = socket.getInputStream();
                os = socket.getOutputStream();

                while (true){
                    byte[] buffer = new byte[128];
                    int count = is.read(buffer);
                    Message msg = new Message();
                    msg.obj = new String (buffer,0,count,"utf-8");
                    handle.sendMessage(msg);

                }

            }catch (Exception e){

            }
        }
    }
}

xml文件布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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"
    android:orientation="vertical"
    >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/open"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="打开蓝牙" />


        <Button
            android:id="@+id/search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="搜索蓝牙" />

        <Button
            android:id="@+id/close"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="关闭蓝牙" />

        <Button
            android:id="@+id/show_list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="显示蓝牙列表" />
    </LinearLayout>


    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

</LinearLayout>

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9006次
    • 积分:249
    • 等级:
    • 排名:千里之外
    • 原创:16篇
    • 转载:7篇
    • 译文:0篇
    • 评论:1条
    最新评论