蓝牙传输

Android工程搭建

清单文件

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH"/>

具体代码

package com.example.day10_lx_2;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
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.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.Toolbar;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

public class Activity extends AppCompatActivity implements View.OnClickListener {
    Button but_open, but_close, but_search, but_bonded;
    ProgressBar proBar;
    BluetoothManager bluetoothManager;
    BluetoothAdapter bluetoothAdapter;
    ListView listView_bonded,listView_search;
    MyAdapter myAdapter_bonded,myAdapter_search;
    ArrayList<BluetoothDevice> list_bonded = new ArrayList<>();
    ArrayList<BluetoothDevice> list_search = new ArrayList<>();
    private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
    String[] strings = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH,Manifest.permission.WRITE_EXTERNAL_STORAGE,
    Manifest.permission.READ_EXTERNAL_STORAGE};
    MyBroad myBroad;
    File file_cai;
    File myFile = new File("/mnt/sdcard/Download/我的菜单.txt");
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==101){
                byte[] str = (byte[])msg.obj;
                try {
                    FileOutputStream fos = new FileOutputStream(myFile);
                    fos.write(str,0,msg.arg1);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }else if(msg.what==202){
                String str = (String)msg.obj;
                Toast.makeText(Activity.this, ""+str, Toast.LENGTH_SHORT).show();
            }else if(msg.what==303){
                proBar.setProgress((Integer) msg.obj);
            }else if(msg.what==404){
                proBar.setMax((Integer) msg.obj);
            }
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            for (int i = 0; i < strings.length; i++) {
                int permission = ActivityCompat.checkSelfPermission(this, strings[i]);
                if (permission == PackageManager.PERMISSION_DENIED) {
                    requestPermissions(strings, 101);
                    break;
                }
            }
        }
        myBroad = new MyBroad();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(myBroad,intentFilter);
        init();

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void init() {
        proBar = findViewById(R.id.proBar);
        but_open = findViewById(R.id.but_open);
        but_close = findViewById(R.id.but_close);
        but_search = findViewById(R.id.but_search);
        but_bonded = findViewById(R.id.but_bonded);
        listView_bonded = findViewById(R.id.list_bonded);
        listView_search = findViewById(R.id.list_search);

        bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

        but_open.setOnClickListener(this);
        but_close.setOnClickListener(this);
        but_search.setOnClickListener(this);
        but_bonded.setOnClickListener(this);

        myAdapter_bonded = new MyAdapter(this,list_bonded);
        myAdapter_search = new MyAdapter(this,list_search);
        listView_bonded.setAdapter(myAdapter_bonded);
        listView_search.setAdapter(myAdapter_search);

        listView_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice bluetoothDevice = list_search.get(position);
                bluetoothDevice.createBond();
            }
        });

        listView_bonded.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = list_bonded.get(position);
                try {
                    BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                    socket.connect();
                    OutputStream os = socket.getOutputStream();
                    File file = Environment.getExternalStorageDirectory();
                    File download = new File(file, "Download");
                    file_cai = new File(download, "js.txt");
                    File my_f = new File("/mnt/sdcard/temp.jpg");
                    FileInputStream fis = new FileInputStream(my_f);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while((len=fis.read(buffer))!=-1){
                        os.write(buffer,0,len);
                    }
                    Toast.makeText(Activity.this, "发送成功", Toast.LENGTH_SHORT).show();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.but_open:
                myOpen();
                break;
            case R.id.but_close:
                bluetoothAdapter.disable();
                break;
            case R.id.but_search:
                bluetoothAdapter.startDiscovery();
                break;
            case R.id.but_bonded:
                myonBonded();
                break;
        }
    }

    private void myonBonded() {
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        list_bonded.clear();
        list_bonded.addAll(bondedDevices);
        myAdapter_bonded.notifyDataSetChanged();
    }

    private void myOpen() {
        Intent intent = new Intent();
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,2000);
        startActivityForResult(intent,101);

        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
                    while(true){
                        final BluetoothSocket socket = serverSocket.accept();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(Activity.this, ""+socket.getRemoteDevice().getName(), Toast.LENGTH_SHORT).show();
                            }
                        });
                        new MyServiceThread(handler,socket).start();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }.start();

    }

    class MyBroad extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                list_search.add(bluetoothDevice);
                myAdapter_search.notifyDataSetChanged();
            }
        }
    }

}

package com.example.day10_lx_2;

import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyServiceThread extends Thread {
    Handler handler;
    BluetoothSocket socket;

    public MyServiceThread(Handler handler, BluetoothSocket socket) {
        this.handler = handler;
        this.socket = socket;
    }

    @Override
    public void run() {
        super.run();
        try {
            InputStream is = socket.getInputStream();
            FileOutputStream fos = new FileOutputStream("/sdcard/我的测试.jpg");
            byte[] buffer = new byte[1024*10];
            int len = 0;
            StringBuffer sb = new StringBuffer();

            byte[] n = new byte[is.available()];

            Message obtain1 = Message.obtain();
            obtain1.what = 404;
            obtain1.obj = n.length;
            handler.sendMessage(obtain1);
            Log.d("xxx",is.available()+"----------------------");
            Log.d("xxx",n.length+"-----================-----------------");

            while ((len = is.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, len));

                Message obtain2 = Message.obtain();
                obtain2.what = 303;
                obtain2.obj = len;
                Log.d("xxx",len+"----------");
                handler.sendMessage(obtain2);

                fos.write(buffer,0,len);
//                if(is.available()<=0){
//                    break;
//                }
            }
            Message obtain = Message.obtain();
            obtain.what = 202;
            obtain.obj = sb.toString();
            handler.sendMessage(obtain);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值