android 蓝牙打印

来源:互联网 发布:永恒之塔数据库 编辑:程序博客网 时间:2024/06/06 05:48

首先需要的权限:

android.permission.BLUETOOTH//允许程序连接到已配对的蓝牙设备android.permission.BLUETOOTH_ADMIN//允许程序发现和配对蓝牙设备

代码:


package har.bluetooth.ui;public interface BlueToothListener { void onFail(String msg); void onStarting(); void onSucceed();  void onConnected();}


package har.bluetooth.ui;import java.io.IOException;import java.io.OutputStream;import java.lang.reflect.Method;import java.util.UUID;import android.app.Activity;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.bluetooth.BluetoothSocket;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;public class BlueToothReceiver extends BroadcastReceiver{private static BlueToothReceiver receiver=null;private BlueToothListener listener;private Activity activity;public BlueToothReceiver(Activity activity,BlueToothListener listener){this.listener=listener;this.activity=activity;}public static BlueToothReceiver getInstance(Activity activity,BlueToothListener listener){if(receiver==null){receiver=new BlueToothReceiver(activity,listener);}return receiver;}private String blueName="Gprinter";private int connectState;private BluetoothAdapter blueAdapter=BluetoothAdapter.getDefaultAdapter();private BluetoothSocket mSocket;@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubString action=intent.getAction();if(BluetoothDevice.ACTION_FOUND.equals(action)){BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if(device.getName().equalsIgnoreCase(blueName)){blueAdapter.cancelDiscovery();    // 获取蓝牙设备的连接状态      connectState = device.getBondState(); if (connectState == BluetoothDevice.BOND_NONE) {// 配对      try {    Method createBondMethod = BluetoothDevice.class.getMethod("createBond");    createBondMethod.invoke(device);    } catch (Exception e) {     e.printStackTrace(); listener.onFail("数据打印异常");}} else if (connectState == BluetoothDevice.BOND_BONDED) {try {    // 连接      connect(device); listener.onConnected();} catch (Exception e) {    e.printStackTrace();  listener.onFail("打印失败");}}}else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){BluetoothDevice cdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);    if (cdevice.getName().equalsIgnoreCase(blueName)) {     connectState = device.getBondState();    switch (connectState) {    case BluetoothDevice.BOND_NONE:    break;    case BluetoothDevice.BOND_BONDING:    break;    case BluetoothDevice.BOND_BONDED:    try {    // 连接      connect(device);listener.onConnected();} catch (Exception e) {    e.printStackTrace();    }    break;    }    }}}}private void connect(BluetoothDevice device) throws Exception {  // 固定的UUID   final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";  UUID uuid = UUID.fromString(SPP_UUID);  mSocket = device.createRfcommSocketToServiceRecord(uuid);  mSocket.connect();  } /** * 发送数据 * @throws IOException  */public void sendData(String data) {if (mSocket == null)   {  listener.onFail("打印失败");return;  }try {                 OutputStream os = mSocket.getOutputStream();   os.write(data.getBytes());  listener.onSucceed();} catch (Exception e) {  // TODO Auto-generated catch block  e.printStackTrace();  listener.onFail("打印失败");}             }private void searchBlueTooth() {// TODO Auto-generated method stubIntentFilter intentFilter = new IntentFilter();    intentFilter.addAction(BluetoothDevice.ACTION_FOUND);    intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);    intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);    activity.registerReceiver(this, intentFilter);    blueAdapter.startDiscovery();  }private void checkBlueTooth() {// TODO Auto-generated method stubif(blueAdapter==null){listener.onFail("该手机不支持蓝牙设备");}else{}}private void checkOpenClose(){if(blueAdapter.isEnabled()){listener.onFail("蓝牙已开启");}else{}}private void openBlueTooth(){if(!blueAdapter.isEnabled()){//直接打开蓝牙设备blueAdapter.enable();//下面是弹出对话框的形式确认打开蓝牙设备/*Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);    startActivity(intent); */}}private void closeBlueTooth(){if(blueAdapter.isEnabled()){blueAdapter.disable();}}private void print(String data){if(blueAdapter==null){listener.onFail("该手机不支持蓝牙设备");}else{if(blueAdapter.isEnabled()){}else{openBlueTooth();}searchBlueTooth();}}public void destory(){activity.unregisterReceiver(this);closeBlueTooth();}}
package har.bluetooth.ui;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener{private TextView tv;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) findViewById(R.id.click);tv.setOnClickListener(this);}public void onClick(View v) {// TODO Auto-generated method stubif (v == tv) {         BlueToothReceiver.getInstance(this, getOnBlueToothListener());}}private BlueToothListener getOnBlueToothListener() {// TODO Auto-generated method stubreturn new BlueToothListener() {@Overridepublic void onSucceed() {// TODO Auto-generated method stubToast.makeText(getApplicationContext(), "打印成功", Toast.LENGTH_SHORT).show();}@Overridepublic void onStarting() {// TODO Auto-generated method stub//dialog}@Overridepublic void onFail(String msg) {// TODO Auto-generated method stubToast.makeText(getApplicationContext(), msg.toString().trim(), Toast.LENGTH_SHORT).show();}@Overridepublic void onConnected() {// TODO Auto-generated method stubBlueToothReceiver.getInstance(MainActivity.this, getOnBlueToothListener()).sendData("草莓当123324UP{PP{");}};}protected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy(); BlueToothReceiver.getInstance(this, getOnBlueToothListener()).destory();}}


经过打印机Gprinter测试,String型数据已打印成功,其他数据还未测试,源码下载地址:http://download.csdn.net/detail/anddroid_lanyan/8582307

0 0