android 蓝牙打印

1. 首先 构造一个打印的业务类

public class PrintBean {

public static final int PRINT_TYPE =1664;

    //蓝牙-名称

    public Stringname;

    //蓝牙-地址

    public Stringaddress;

    //蓝牙-设备类型

    public int type;

    //蓝牙-是否已经匹配

    public boolean isConnect;

    BluetoothDevicedevice;

    /**

    * @param devicee 蓝牙设备对象

*/

    public PrintBean(BluetoothDevice devicee) {

this.name = TextUtils.isEmpty(devicee.getName()) ?"未知" : devicee.getName();

        this.address = devicee.getAddress();

        this.isConnect = devicee.getBondState() == BluetoothDevice.BOND_BONDED;

        this.type = devicee.getBluetoothClass().getDeviceClass();

    }

public StringgetName() {

return name;

    }

public StringgetAddress() {

return address;

    }

    public int getTypeIcon() {

if (type ==260) {

return R.drawable.ic_computer_black_24dp;

        }else if (type ==PRINT_TYPE) {

return R.drawable.ic_local_printshop_black_24dp;

        }else if (type ==524) {

return R.drawable.ic_phone_android_black_24dp;

        }else {

return R.drawable.ic_issue;

        }

}

public StringgetDeviceType(View view) {

if (type ==PRINT_TYPE) {

view.setSelected(true);

            return isConnect ?"选择打印" :"点击连接";

        }else {

view.setSelected(false);

            return "非打印设备";

        }

}

public int getType() {

return type;

    }

public boolean isConnect() {

return isConnect;

    }

public BluetoothDevicegetDevice() {

return device;

    }

public void setConnect(boolean connect) {

isConnect = connect;

    }

}

2.创建一个Activity类 

public class PrintActivityextends BaseActivity {

private ContextmContext = PrintActivity.this;

    //设备列表

    private ListViewlistView;

    private ArrayListmBluetoothDevicesDatas;

    private PrintAdapteradapter;

    //蓝牙适配器

    private BluetoothAdaptermBluetoothAdapter;

    //请求的code

    public static final int REQUEST_ENABLE_BT =1;

    private SwitchmSwitch;

    private FloatingActionButtonmFloatingActionButton;

    private ProgressBarmProgressBar;

    private TextViewsearchHint;

    private  IntentFilterfilter;

    /**

* 启动打印页面

*

    * @param printContent 要打印的内容

*/

    public static void starUi(Context context, String printContent) {

Intent intent =new Intent(context, PrintActivity.class);

        intent.putExtra("printContent", printContent);

        context.startActivity(intent);

    }

private  StringprintContent;

    private Stringaddress;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_print);

        //广播注册

        filter =new IntentFilter(BluetoothDevice.ACTION_FOUND);

        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

//初始化

        android.support.v7.app.ActionBar actionBar = getSupportActionBar();

        if(actionBar !=null){

actionBar.setHomeButtonEnabled(true);

            actionBar.setDisplayHomeAsUpEnabled(true);

        }

setTitle(R.string.select_printing_device);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        mSwitch = (Switch) findViewById(R.id.switch1);

        mFloatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton);

        mProgressBar = (ProgressBar) findViewById(R.id.progressBar3);

        searchHint = (TextView) findViewById(R.id.searchHint);

        listView = (ListView) findViewById(R.id.listView);

        mBluetoothDevicesDatas =new ArrayList<>();

        printContent=getIntent().getStringExtra("printContent");

        Log.e("content",printContent);

        adapter =new PrintAdapter(this, mBluetoothDevicesDatas, TextUtils.isEmpty(printContent)?"\n 内容为空 \n\n":printContent);

//        adapter = new PrintAdapter(this, mBluetoothDevicesDatas, TextUtils.isEmpty(printContent)?name:printContent);

        listView.setAdapter(adapter);

        chechBluetooth();

        addViewListener();

    }

@Override

    public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()){

case android.R.id.home:

finish();

break;

        }

return true;

    }

/**

* 添加View的监听

*/

    private void addViewListener() {

//蓝牙的状态

        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if (isChecked) {

openBluetooth();

                    setViewStatus(true);

                }else {

closeBluetooth();

                }

}

});

        //重新搜索

        mFloatingActionButton.setOnClickListener(new View.OnClickListener() {

@Override

            public void onClick(View v) {

if (mSwitch.isChecked()) {

searchDevices();

                    setViewStatus(true);

                }else {

openBluetooth();

                    setViewStatus(true);

                }

}

});

    }

/**

* 打开蓝牙

*/

    public void openBluetooth() {

Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 设置蓝牙可见性,最多300秒

        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 20);

        startActivityForResult(intent, REQUEST_ENABLE_BT);

    }

/**

* 关闭蓝牙

*/

    public void closeBluetooth() {

mBluetoothAdapter.disable();

    }

/**

* 判断有没有开启蓝牙

*/

    private void chechBluetooth() {

//没有开启蓝牙

        if (mBluetoothAdapter !=null) {

if (!mBluetoothAdapter.isEnabled()) {

Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 设置蓝牙可见性,最多300秒

                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 20);

                startActivityForResult(intent, REQUEST_ENABLE_BT);

                setViewStatus(true);

                //开启蓝牙

            }else {

searchDevices();

                setViewStatus(true);

                mSwitch.setChecked(true);

            }

}

}

/**

* 搜索状态调整

*

    * @param isSearch 是否开始搜索

*/

    private void setViewStatus(boolean isSearch) {

if (isSearch) {

mFloatingActionButton.setVisibility(View.GONE);

            searchHint.setVisibility(View.VISIBLE);

            mProgressBar.setVisibility(View.VISIBLE);

        }else {

mFloatingActionButton.setVisibility(View.VISIBLE);

            mProgressBar.setVisibility(View.GONE);

            searchHint.setVisibility(View.GONE);

        }

}

@Override

    protected void onDestroy() {

super.onDestroy();

        unregisterReceiver(mReceiver);

    }

/**

* 搜索蓝牙设备

*/

    public void searchDevices() {

mBluetoothDevicesDatas.clear();

        adapter.notifyDataSetChanged();

        //开始搜索蓝牙设备

        mBluetoothAdapter.startDiscovery();

    }

/**

* 通过广播搜索蓝牙设备

*/

    private final BroadcastReceivermReceiver =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) {

addBluetoothDevice(device);

                    //没有匹配的设备

                }else {

addBluetoothDevice(device);

                }

adapter.notifyDataSetChanged();

                //搜索完成

            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

setViewStatus(false);

            }

}

/**

* 添加数据

        * @param device 蓝牙设置对象

*/

        private void addBluetoothDevice(BluetoothDevice device) {

for (int i =0; i

if (device.getAddress().equals(mBluetoothDevicesDatas.get(i).getAddress())) {

mBluetoothDevicesDatas.remove(i);

                }

}

if (device.getBondState() == BluetoothDevice.BOND_BONDED && device.getBluetoothClass().getDeviceClass() ==PRINT_TYPE) {

mBluetoothDevicesDatas.add(0, new PrintBean(device));

            }else {

mBluetoothDevicesDatas.add(new PrintBean(device));

            }

}

};

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

        if (resultCode ==RESULT_OK && requestCode ==REQUEST_ENABLE_BT) {

Log.e("text", "开启蓝牙");

            searchDevices();

            mSwitch.setChecked(true);

            mBluetoothDevicesDatas.clear();

            adapter.notifyDataSetChanged();

        }else if (resultCode ==RESULT_CANCELED && requestCode ==REQUEST_ENABLE_BT) {

Log.e("text", "没有开启蓝牙");

            mSwitch.setChecked(false);

            setViewStatus(false);

        }

}

}

3. 适配器


public class PrintAdapterextends BaseAdapter {

private ArrayListmBluetoothDevicesDatas;

    private ContextmContext;

    //蓝牙适配器

    private BluetoothAdaptermBluetoothAdapter;

    //蓝牙socket对象

    private BluetoothSocketmmSocket;

    private UUIDuuid;

    //打印的输出流

    private static OutputStreamoutputStream =null;

    //搜索弹窗提示

    ProgressDialogprogressDialog =null;

    private final int exceptionCod =100;

    //打印的内容

    private StringmPrintContent;

    private  ConnectThreadconnectThread;

    //在打印异常时更新ui

    Handlerhandler =new Handler() {

@Override

        public void handleMessage(Message msg) {

super.handleMessage(msg);

            if (msg.what ==exceptionCod) {

Toast.makeText(mContext, "打印发送失败,请稍后再试", Toast.LENGTH_SHORT).show();

                if (progressDialog !=null) {

progressDialog.dismiss();

                }

}

}

};

    /**

    * @param context                上下文

    * @param mBluetoothDevicesDatas 设备列表

    * @param printContent          打印的内容

*/

    public PrintAdapter(Context context, ArrayList mBluetoothDevicesDatas, String printContent) {

this.mBluetoothDevicesDatas = mBluetoothDevicesDatas;

        mContext = context;

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        mPrintContent = printContent;

        uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    }

public int getCount() {

return mBluetoothDevicesDatas.size();

    }

@Override

    public ObjectgetItem(int position) {

return position;

    }

@Override

    public long getItemId(int position) {

return position;

    }

@Override

    public ViewgetView(final int position, View convertView, ViewGroup parent) {

convertView = LayoutInflater.from(mContext).inflate(R.layout.bluetooth_itme, null);

        View icon = convertView.findViewById(R.id.icon);

        TextView name = (TextView) convertView.findViewById(R.id.name);

        TextView address = (TextView) convertView.findViewById(R.id.address);

        TextView start = (TextView) convertView.findViewById(R.id.start);

        final PrintBean dataBean =mBluetoothDevicesDatas.get(position);

        icon.setBackgroundResource(dataBean.getTypeIcon());

        name.setText(dataBean.name);

        address.setText(dataBean.isConnect ?"已连接" :"未连接");

        start.setText(dataBean.getDeviceType(start));

        //点击连接与打印

        convertView.setOnClickListener(new View.OnClickListener() {

@Override

            public void onClick(View v) {

try {

//如果已经连接并且是打印机

                    if (dataBean.isConnect &&dataBean.getType() ==PRINT_TYPE) {

if (mBluetoothAdapter.isEnabled()) {

if (connectThread !=null){

try {

mmSocket.close();

                                }catch (IOException e) {

e.printStackTrace();

                                }

connectThread=null;

                            }

connectThread =new ConnectThread(mBluetoothAdapter.getRemoteDevice(dataBean.address));

                            connectThread.start();

                            Log.e("address",dataBean.address);

                            progressDialog = ProgressDialog.show(mContext, "提示", "正在打印...", true);

                        }else {

Toast.makeText(mContext, "蓝牙没有打开", Toast.LENGTH_SHORT).show();

                        }

//没有连接

                    }else {

//是打印机

                        if (dataBean.getType() ==PRINT_TYPE) {

setConnect(mBluetoothAdapter.getRemoteDevice(dataBean.address), position);

                            //不是打印机

                        }else {

Toast.makeText(mContext, "该设备不是打印机", Toast.LENGTH_SHORT).show();

                        }

}

}catch (Exception e) {

e.printStackTrace();

                }

}

});

        return convertView;

    }

/**

* 匹配设备

*

    * @param device 设备

*/

    private void setConnect(BluetoothDevice device, int position) {

try {

Method createBondMethod = BluetoothDevice.class.getMethod("createBond");

            createBondMethod.invoke(device);

            mBluetoothDevicesDatas.get(position).setConnect(true);

            notifyDataSetChanged();

        }catch (Exception e) {

e.printStackTrace();

        }

}

/**

* 发送数据

*/

    public void send(String sendData) {

try {

byte[] data = sendData.getBytes("gbk");

            outputStream.write(data, 0, data.length);

            outputStream.flush();

            outputStream.close();

            progressDialog.dismiss();

            Log.e("打印内容", Arrays.toString(data));

//            ConnectThread.sleep(5000);

          ConnectThread.sleep(1000);

        }catch (IOException e) {

e.printStackTrace();

            Log.e("打印内容", e.getMessage());

            handler.sendEmptyMessage(exceptionCod); // 向Handler发送消息,更新UI

        }catch (InterruptedException e) {

e.printStackTrace();

        }

}

/**

* 连接为客户端

*/

    private class ConnectThreadextends Thread {

public ConnectThread(BluetoothDevice device) {

try {

mmSocket = device.createRfcommSocketToServiceRecord(uuid);

            }catch (IOException e) {

e.printStackTrace();

            }

}

public void run() {

//取消的发现,因为它将减缓连接

            mBluetoothAdapter.cancelDiscovery();

            try {

//连接socket

                mmSocket.connect();

                //连接成功获取输出流

                outputStream =mmSocket.getOutputStream();

                send(mPrintContent);

                Log.e("发送内容",mPrintContent);

            }catch (Exception connectException) {

Log.e("test", "连接失败");

                connectException.printStackTrace();

                //异常时发消息更新UI

                Message msg =new Message();

                msg.what =exceptionCod;

                // 向Handler发送消息,更新UI

                handler.sendMessage(msg);

                try {

mmSocket.close();

                }catch (Exception closeException) {

closeException.printStackTrace();

                }

return;

            }

}

}

}

bluetooth_itme.xml 布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:orientation="horizontal"

    android:padding="15dp">

        android:id="@+id/icon"

        android:layout_width="15dp"

        android:layout_height="15dp"

        android:layout_gravity="center_vertical"

        android:layout_marginRight="10dp"

        android:background="@mipmap/ic_launcher"

        android:text="名称" />

        android:id="@+id/name"

        android:layout_width="0dp"

        android:layout_height="wrap_content"

        android:layout_weight="2"

        android:text="名称" />

        android:id="@+id/address"

        android:layout_width="0dp"

        android:layout_height="wrap_content"

        android:layout_weight="1"

        android:text="地址" />

        android:id="@+id/start"

        android:layout_width="85dp"

        android:layout_height="wrap_content"

        android:background="@drawable/bg_print"

        android:gravity="center"

        android:padding="5dp"

        android:textSize="14sp"

        android:text="非打印设备"

        android:textColor="@color/select_print_color" />

</LinearLayout>

activity_print.xml布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="@color/colorWhite"

    android:orientation="vertical">

        android:layout_width="match_parent"

        android:layout_height="50dp"

        android:gravity="center"

        android:paddingLeft="15dp"

        android:paddingRight="15dp">

            android:layout_width="0dp"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:text="蓝牙开关"

            android:textColor="#ff000000"

            android:textSize="14sp" />

        <Switch xmlns:app="http://schemas.android.com/apk/res-auto"

            android:id="@+id/switch1"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_marginLeft="16dp"

            android:layout_marginStart="16dp"

            android:textColor="@color/colorAccent"

            android:textSize="16sp" />

        android:layout_width="match_parent"

        android:layout_height="1dp"

        android:background="#ffcccccc" />

        android:layout_width="match_parent"

        android:layout_height="50dp"

        android:paddingLeft="15dp"

        android:paddingRight="15dp">

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerVertical="true"

            android:text="搜索"

            android:textColor="#ff000000"

            android:textSize="14sp" />

            android:id="@+id/searchHint"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerHorizontal="true"

            android:layout_centerVertical="true"

            android:text="搜索中..."

            android:textColor="#FF4081"

            android:textSize="14sp" />

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_alignParentRight="true"

            android:layout_centerVertical="true">

                android:id="@+id/floatingActionButton"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_gravity="center"

                android:clickable="true"

                app:fabSize="mini"

                app:srcCompat="@drawable/ic_search_black_24dp" />

                android:id="@+id/progressBar3"

                style="?android:attr/progressBarStyle"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_gravity="center" />

        android:layout_width="match_parent"

        android:layout_height="8dp"

        android:background="#ffcccccc" />

        android:id="@+id/listView"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" />


ic_computer_black_24dp.xml drawable文件

<vector xmlns:android="http://schemas.android.com/apk/res/android"

    android:width="24dp"

    android:height="24dp"

    android:viewportHeight="24.0"

    android:viewportWidth="24.0">

        android:fillColor="#FFcccccc"

        android:pathData="M20,18c1.1,0 1.99,-0.9 1.99,-2L22,6c0,-1.1 -0.9,-2 -2,-2H4c-1.1,0 -2,0.9 -2,2v10c0,1.1 0.9,2 2,2H0v2h24v-2h-4zM4,6h16v10H4V6z" />

</vector>

ic_local_printshop_black_24dp.xml 文件

<vector xmlns:android="http://schemas.android.com/apk/res/android"

        android:width="24dp"

        android:height="24dp"

        android:viewportWidth="24.0"

        android:viewportHeight="24.0">

        android:fillColor="#FFcccccc"

        android:pathData="M19,8L5,8c-1.66,0 -3,1.34 -3,3v6h4v4h12v-4h4v-6c0,-1.66 -1.34,-3 -3,-3zM16,19L8,19v-5h8v5zM19,12c-0.55,0 -1,-0.45 -1,-1s0.45,-1 1,-1 1,0.45 1,1 -0.45,1 -1,1zM18,3L6,3v4h12L18,3z"/>

</vector>

ic_phone_android_black_24dp.xml 文件

<vector xmlns:android="http://schemas.android.com/apk/res/android"

        android:width="24dp"

        android:height="24dp"

        android:viewportWidth="24.0"

        android:viewportHeight="24.0">

        android:fillColor="#FFcccccc"

        android:pathData="M16,1L8,1C6.34,1 5,2.34 5,4v16c0,1.66 1.34,3 3,3h8c1.66,0 3,-1.34 3,-3L19,4c0,-1.66 -1.34,-3 -3,-3zM14,21h-4v-1h4v1zM17.25,18L6.75,18L6.75,4h10.5v14z"/>

</vector>

ic_issue.xml文件

<vector xmlns:android="http://schemas.android.com/apk/res/android"

    android:width="24dp"

    android:height="24dp"

    android:viewportHeight="1024.0"

    android:viewportWidth="1024.0">

        android:fillColor="#FFcccccc"

        android:pathData="M506.7,135.7c-202.2,0 -366.1,163.9 -366.1,366.1 0,202.2 163.9,366.1 366.1,366.1 202.2,0 366.1,-163.9 366.1,-366.1C872.8,299.6 708.9,135.7 506.7,135.7L506.7,135.7zM504.4,716.2c-21.2,0 -38.5,-16.9 -38.5,-37.7 0,-20.8 17.2,-37.7 38.5,-37.7 21.2,0 38.5,16.9 38.5,37.7C542.9,699.3 525.6,716.2 504.4,716.2L504.4,716.2zM649.5,458.5c-10.6,16.6 -33.1,39.3 -67.6,68 -17.9,14.8 -28.9,26.8 -33.2,35.8 -4.3,9 -6.3,25.2 -5.9,48.5l-76.9,0c-0.2,-11 -0.3,-17.8 -0.3,-20.2 0,-24.9 4.1,-45.4 12.4,-61.4 8.2,-16.1 24.7,-34.2 49.4,-54.2 24.7,-20.1 39.5,-33.2 44.3,-39.5 7.4,-9.8 11.2,-20.7 11.2,-32.5 0,-16.4 -6.6,-30.5 -19.8,-42.2 -13.2,-11.7 -30.9,-17.6 -53.3,-17.6 -21.5,0 -39.5,6.1 -54,18.3 -14.5,12.2 -26.9,39.1 -29.9,55.8 -2.8,15.7 -78.6,22.3 -77.7,-9.5 0.9,-31.9 17.5,-66.5 46,-91.6 28.4,-25.1 65.8,-37.6 112,-37.6 48.6,0 87.3,12.7 116,38.1 28.7,25.4 43.1,55 43.1,88.7C665.3,424.2 660,441.8 649.5,458.5L649.5,458.5zM649.5,458.5" />

</vector>

清单文件中需要的权限

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

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

注意:如果你需要连接一次蓝牙后无需在连接 进行打印,需要注意以下代码

private Stringaddress ="";

private BluetoothAdaptermBluetoothAdapter;

private IntentFilterfilter;

private  Stringaction;

private UUIDuuid;

在onCreate 方法中添加

filter =new IntentFilter(BluetoothDevice.ACTION_FOUND);

filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

registerReceiver(mReceiver, filter);

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

mBluetoothAdapter.startDiscovery();

uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");


/**

* 通过广播搜索蓝牙设备

*/

    private ArrayListmBluetoothDevicesDatas =new ArrayList<>();

    private BluetoothSocketmmSocket;

    private static OutputStreamoutputStream =null;

    private final BroadcastReceivermReceiver =new BroadcastReceiver() {

public void onReceive(Context context, Intent intent) {

action = intent.getAction();

            // 把搜索的设置添加到集合中

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                //已经匹配的设备

                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {

addBluetoothDevice(device);

                    address = device.getAddress();

//                    progressDialog = ProgressDialog.show(HistoryAddActivity.this, "提示", "正在打印...", true);

                    Log.e("his address",address);

                    //没有匹配的设备

                }else {

addBluetoothDevice(device);

                }

//搜索完成

            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

//                setViewStatus(false);

            }

}

/**

* 添加数据

    * @param device 蓝牙设置对象

*/

    private void addBluetoothDevice(BluetoothDevice device) {

for (int i =0; i

if (device.getAddress().equals(mBluetoothDevicesDatas.get(i).getAddress())) {

mBluetoothDevicesDatas.remove(i);

            }

}

if (device.getBondState() == BluetoothDevice.BOND_BONDED && device.getBluetoothClass().getDeviceClass() ==PRINT_TYPE) {

mBluetoothDevicesDatas.add(0, new PrintBean(device));

        }else {

mBluetoothDevicesDatas.add(new PrintBean(device));

        }

}

};

/**

* 发送数据

*/

    public void send(String datamessage) {

try {

if (mmSocket !=null) {

mmSocket.connect();

                //连接成功获取输出流

            }

outputStream =mmSocket.getOutputStream();

            byte[] data = datamessage.getBytes("GBK");

            outputStream.write(data, 0, data.length);

            outputStream.flush();

//            outputStream.close();

            progressDialog.dismiss();

//            Log.e("打印内容",Arrays.toString(data));

//            ConnectThread.sleep(1000);

        }catch (IOException e) {

e.printStackTrace();

            Log.e("打印内容",e.getMessage());

            handler.sendEmptyMessage(exceptionCod); // 向Handler发送消息,更新UI

        }

}

private class ConnectThreadextends Thread {

Stringdatamessage;

        public ConnectThread(BluetoothDevice device,String datamessages) {

datamessage = datamessages;

            BluetoothSocket tmp =null;

            try {

tmp = device.createRfcommSocketToServiceRecord(uuid);

            }catch (IOException e) {

e.printStackTrace();

            }

mmSocket = tmp;

        }

public void run() {

//取消的发现,因为它将减缓连接

            mBluetoothAdapter.cancelDiscovery();

            try {

send(datamessage);

                Log.e("发送内容",datamessage);

            }catch (Exception connectException) {

Log.e("test", "连接失败");

                connectException.printStackTrace();

                //异常时发消息更新UI

                try {

mmSocket.close();

                }catch (Exception closeException) {

closeException.printStackTrace();

                }

return;

            }

}

}

@Override

    protected void onResume() {

super.onResume();

            if (connectThread !=null){

try {

mmSocket.close();

                }catch (IOException e) {

e.printStackTrace();

                }

connectThread =null;

        }else {

filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

            registerReceiver(mReceiver, filter);

        }

}

@Override

    protected void onDestroy() {

super.onDestroy();

        if (connectThread !=null){

try {

mmSocket.close();

            }catch (IOException e) {

e.printStackTrace();

            }

connectThread=null;

        }

unregisterReceiver(mReceiver);

    }

注意:一定要在activity销毁的时候清空sockt,不然会出现打印信息不完整。

打印功能触发的时候 跟据address 是否为空 判定是否有连接设备,


if (mBluetoothAdapter.isEnabled()){

if (address.equals("")){

PrintActivity.starUi(HistoryItemDetailsActivity.this, print);

    }else {

connectThread =new ConnectThread(mBluetoothAdapter.getRemoteDevice(address),print);

      connectThread.start();

        progressDialog = ProgressDialog.show(HistoryItemDetailsActivity.this, "提示", "正在打印...", true);

    }

}else {

Log.e("text", "没有开启蓝牙");

    PrintActivity.starUi(HistoryItemDetailsActivity.this, print);

}

希望对你有帮助!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容