精华内容
下载资源
问答
  • 上图是一个WORD文档,我想要制作一个手机软件,实现以下功能: 1.能够方便录入检查单位、时间2项内容。 2.左侧2个单元格,要方便插入图片,并...4.软件有打印按钮,能够直接打印出来。手机上有三星共享打印组件。

     

    上图是一个WORD文档,我想要制作一个手机软件,实现以下功能:

    1.能够方便录入检查单位、时间2项内容。

    2.左侧2个单元格,要方便插入图片,并自动适用单元格大小。

    3.右侧2个单元格,录入文字。

    4.软件有打印按钮,能够直接打印出来。手机上有三星的共享打印组件。

    展开全文
  • 苹果手机有一个叫“隔空打印功能,急需打印的时候不需要开电脑也不必将照片或文件传到电脑,就可以打印,下面我们来了解一下这个新技巧。 首先,苹果手机一个扫描功能,我们打开备忘录-新建-点这里加号-...

    很多人应该都试过急需打印的时候,身边却没有电脑这种情况吧?只用手机怎么打印呢?苹果手机有一个叫“隔空打印”功能,急需打印的时候不需要开电脑也不必将照片或文件传到电脑,就可以打印,下面我们来了解一下这个新技巧。

    首先,苹果手机都有一个扫描功能,我们打开备忘录-新建-点这里的加号-扫描文稿之后点储存。

    然后扫完之后点右上角的小箭头就可以看到-打印-选择打印机-选择几份-几页,这样就可以"隔空打印"啦.

    最后还要说一下,除了苹果手机能打印,我们安卓手机也是可以的哦,只不过得先下载一个打印软件,然后打开WIFI设置,

    连接打印机之后选择打印照片或文档直接打印,用手机打印是不是大大的提高了办公效率了呢?这样打印出来的资料质量也好,操作更方便更快捷。学会了给我点个赞哦!

    展开全文
  • 安卓手机连接蓝牙打印机实现打印功能

    万次阅读 多人点赞 2013-09-22 14:22:48
    最近在做一个安卓应用,其中一个需求是要求用蓝牙连接打印机实现打印功能。一开始没有一点头绪,网上找了很多资料也找不到有用数据。所以自己就去研究,最终,功夫不负有心人,顺利完成了这个功能。下边贴出我...

    最近在做一个安卓应用,其中有一个需求是要求用蓝牙连接打印机实现打印功能。一开始没有一点头绪,网上找了很多资料也找不到有用的数据。所以自己就去研究,最终,功夫不负有心人,顺利的完成了这个功能。下边贴出我写的代码,共有需要的IT哥们参考学习。

    完整源码下载

    我们先看看运行效果图吧。。。

    1.这是主界面的效果图


    贴上布局文件的代码:bluetooth_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <Button
            android:id="@+id/openBluetooth_tb"
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="18dp"
            android:layout_marginTop="5dp"
            android:text="打开蓝牙" />
    
        <Button
            android:id="@+id/searchDevices"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/openBluetooth_tb"
            android:layout_marginTop="20dp"
            android:text="搜索设备" />
    
        <View
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/searchDevices"
            android:background="@android:color/darker_gray" />
    
        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_marginTop="125dp"
            android:orientation="vertical" >
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="未配对设备" />
    
            <ListView
                android:id="@+id/unbondDevices"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
    
        <View
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/searchDevices"
            android:layout_marginTop="160dp"
            android:background="@android:color/darker_gray" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="190dp"
            android:layout_marginTop="288dp"
            android:orientation="vertical" >
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="已配对设备" />
              <ListView
                android:id="@+id/bondDevices"
                android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignParentLeft="true"
               android:layout_below="@+id/linearLayout1" >
             </ListView>
        </LinearLayout>
    
        <Button
            android:id="@+id/return_Bluetooth_btn"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_above="@+id/searchDevices"
            android:layout_alignParentLeft="true"
            android:text="返回" />
    
    </RelativeLayout>


    从上边的布局文件中不难看出,其中有两个ListView,OK,那下边贴出对应的两个item布局文件

      --> 第一个item:unbonddevice_item.xml

    <?xml version="1.0" encoding="utf-8"?>  
    <RelativeLayout
        android:layout_width="match_parent"  
        android:layout_height="match_parent" >  
      
        <TextView  
            android:id="@+id/device_name"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_alignParentLeft="true"  
            android:layout_alignParentTop="true"  
            android:text="未绑定设备"  
            android:textAppearance="?android:attr/textAppearanceLarge" />  
      
    </RelativeLayout>

    -->第二个item:bonddevice_item.xml

    <?xml version="1.0" encoding="utf-8"?>  
    <RelativeLayout
        android:layout_width="match_parent"  
        android:layout_height="match_parent" >  
      
        <TextView  
            android:id="@+id/device_name"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_alignParentLeft="true"  
            android:layout_alignParentTop="true"  
            android:text="已绑定设备"  
            android:textAppearance="?android:attr/textAppearanceLarge" />  
      
    </RelativeLayout>

    2.还有另外一个布局文件,就是当点击已绑定蓝牙设备下边的某个item时进入打印的界面,不多说,看图!



    代码如下:printdata_layout.xml

    <?xml version="1.0" encoding="utf-8"?>  
    <RelativeLayout  
        android:layout_width="match_parent"  
        android:layout_height="match_parent" >  
      
        <EditText  
            android:id="@+id/print_data"  
            android:layout_width="match_parent"  
            android:layout_height="200dp"  
            android:layout_alignParentLeft="true"  
            android:layout_alignParentTop="true"  
            android:layout_marginTop="46dp" >  
        </EditText>  
      
        <TextView  
            android:id="@+id/device_name"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_alignParentLeft="true"  
            android:layout_alignParentTop="true"  
            android:layout_marginTop="16dp"  
            android:text="Large Text"  
            android:textAppearance="?android:attr/textAppearanceLarge" />  
      
        <TextView  
            android:id="@+id/connect_state"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_alignBaseline="@+id/device_name"  
            android:layout_alignBottom="@+id/device_name"  
            android:layout_marginLeft="42dp"  
            android:layout_toRightOf="@+id/device_name"  
            android:text="Large Text"  
            android:textAppearance="?android:attr/textAppearanceLarge" />  
      
        <Button  
            android:id="@+id/send"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_alignParentLeft="true"  
            android:layout_below="@+id/print_data"  
            android:layout_marginTop="21dp"  
            android:text="打印" />  
      
        <Button  
            android:id="@+id/command"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:layout_alignParentLeft="true"  
            android:layout_below="@+id/send"  
            android:text="指令" />  
          
    </RelativeLayout>

    至此,布局文件就搞定了,接下来就要编写java代码了。主要有一下这么几个类,一个一个来哈

    BluetoothActivity.java

    这个类的主要作用是初始化主界面,看代码

    public class BluetoothActivity extends Activity {  
        private Context context = null;  
      
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            this.context = this;  
            setTitle("蓝牙打印");  
            setContentView(R.layout.bluetooth_layout);  
            this.initListener();  
        }  
      
        private void initListener() {  
            ListView unbondDevices = (ListView) this  
                    .findViewById(R.id.unbondDevices);  
            ListView bondDevices = (ListView) this.findViewById(R.id.bondDevices);  
            Button switchBT = (Button) this.findViewById(R.id.openBluetooth_tb);  
            Button searchDevices = (Button) this.findViewById(R.id.searchDevices);  
      
            BluetoothAction bluetoothAction = new BluetoothAction(this.context,  
                    unbondDevices, bondDevices, switchBT, searchDevices,  
                    BluetoothActivity.this);  
      
            Button returnButton = (Button) this  
                    .findViewById(R.id.return_Bluetooth_btn);  
            bluetoothAction.setSearchDevices(searchDevices);  
            bluetoothAction.initView();  
      
            switchBT.setOnClickListener(bluetoothAction);  
            searchDevices.setOnClickListener(bluetoothAction);  
            returnButton.setOnClickListener(bluetoothAction);  
        }  
        //屏蔽返回键的代码:  
        public boolean onKeyDown(int keyCode,KeyEvent event)  
        {  
            switch(keyCode)  
            {  
                case KeyEvent.KEYCODE_BACK:return true;  
            }  
            return super.onKeyDown(keyCode, event);  
        }  
    }

    BluetoothAction.java

    这个类顾名思义,是处理bluetoothActivity中各种操作事件的action类,看代码


    public class BluetoothAction implements OnClickListener {  
      
        private Button switchBT = null;  
        private Button searchDevices = null;  
        private Activity activity = null;  
      
        private ListView unbondDevices = null;  
        private ListView bondDevices = null;  
        private Context context = null;  
        private BluetoothService bluetoothService = null;  
      
        public BluetoothAction(Context context, ListView unbondDevices,  
                ListView bondDevices, Button switchBT, Button searchDevices,  
                Activity activity) {  
            super();  
            this.context = context;  
            this.unbondDevices = unbondDevices;  
            this.bondDevices = bondDevices;  
            this.switchBT = switchBT;  
            this.searchDevices = searchDevices;  
            this.activity = activity;  
            this.bluetoothService = new BluetoothService(this.context,  
                    this.unbondDevices, this.bondDevices, this.switchBT,  
                    this.searchDevices);  
        }  
      
        public void setSwitchBT(Button switchBT) {  
            this.switchBT = switchBT;  
        }  
      
        public void setSearchDevices(Button searchDevices) {  
            this.searchDevices = searchDevices;  
        }  
      
        public void setUnbondDevices(ListView unbondDevices) {  
            this.unbondDevices = unbondDevices;  
        }  
      
        /** 
         * 初始化界面 
         */  
        public void initView() {  
      
            if (this.bluetoothService.isOpen()) {  
                System.out.println("蓝牙有开!");  
                switchBT.setText("关闭蓝牙");  
            }  
            if (!this.bluetoothService.isOpen()) {  
                System.out.println("蓝牙没开!");  
                this.searchDevices.setEnabled(false);  
            }  
        }  
      
        private void searchDevices() {  
            bluetoothService.searchDevices();  
        }  
      
        /** 
         * 各种按钮的监听 
         */  
        @Override  
        public void onClick(View v) {  
            if (v.getId() == R.id.searchDevices) {  
                this.searchDevices();  
            } else if (v.getId() == R.id.return_Bluetooth_btn) {  
                activity.finish();  
            } else if (v.getId() == R.id.openBluetooth_tb) {  
                if (!this.bluetoothService.isOpen()) {  
                    // 蓝牙关闭的情况  
                    System.out.println("蓝牙关闭的情况");  
                    this.bluetoothService.openBluetooth(activity);  
                } else {  
                    // 蓝牙打开的情况  
                    System.out.println("蓝牙打开的情况");  
                    this.bluetoothService.closeBluetooth();  
      
                }  
      
            }  
        }  
      
    }



    这个类会把各种请求动作分门别类,交给BluetoothService.java来处理,看代码


    public class BluetoothService {  
        private Context context = null;  
        private BluetoothAdapter bluetoothAdapter = BluetoothAdapter  
                .getDefaultAdapter();  
        private ArrayList<BluetoothDevice> unbondDevices = null; // 用于存放未配对蓝牙设备  
        private ArrayList<BluetoothDevice> bondDevices = null;// 用于存放已配对蓝牙设备  
        private Button switchBT = null;  
        private Button searchDevices = null;  
        private ListView unbondDevicesListView = null;  
        private ListView bondDevicesListView = null;  
      
        /** 
         * 添加已绑定蓝牙设备到ListView 
         */  
        private void addBondDevicesToListView() {  
            ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();  
            int count = this.bondDevices.size();  
            System.out.println("已绑定设备数量:" + count);  
            for (int i = 0; i < count; i++) {  
                HashMap<String, Object> map = new HashMap<String, Object>();  
                map.put("deviceName", this.bondDevices.get(i).getName());  
                data.add(map);// 把item项的数据加到data中  
            }  
            String[] from = { "deviceName" };  
            int[] to = { R.id.device_name };  
            SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data,  
                    R.layout.bonddevice_item, from, to);  
            // 把适配器装载到listView中  
            this.bondDevicesListView.setAdapter(simpleAdapter);  
      
            this.bondDevicesListView  
                    .setOnItemClickListener(new OnItemClickListener() {  
      
                        @Override  
                        public void onItemClick(AdapterView<?> arg0, View arg1,  
                                int arg2, long arg3) {  
                            BluetoothDevice device = bondDevices.get(arg2);  
                            Intent intent = new Intent();  
                            intent.setClassName(context,  
                                    "com.lifeng.jdxt.view.PrintDataActivity");  
                            intent.putExtra("deviceAddress", device.getAddress());  
                            context.startActivity(intent);  
                        }  
                    });  
      
        }  
      
        /** 
         * 添加未绑定蓝牙设备到ListView 
         */  
        private void addUnbondDevicesToListView() {  
            ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();  
            int count = this.unbondDevices.size();  
            System.out.println("未绑定设备数量:" + count);  
            for (int i = 0; i < count; i++) {  
                HashMap<String, Object> map = new HashMap<String, Object>();  
                map.put("deviceName", this.unbondDevices.get(i).getName());  
                data.add(map);// 把item项的数据加到data中  
            }  
            String[] from = { "deviceName" };  
            int[] to = { R.id.device_name };  
            SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data,  
                    R.layout.unbonddevice_item, from, to);  
      
            // 把适配器装载到listView中  
            this.unbondDevicesListView.setAdapter(simpleAdapter);  
      
            // 为每个item绑定监听,用于设备间的配对  
            this.unbondDevicesListView  
                    .setOnItemClickListener(new OnItemClickListener() {  
      
                        @Override  
                        public void onItemClick(AdapterView<?> arg0, View arg1,  
                                int arg2, long arg3) {  
                            try {  
                                Method createBondMethod = BluetoothDevice.class  
                                        .getMethod("createBond");  
                                createBondMethod  
                                        .invoke(unbondDevices.get(arg2));  
                                // 将绑定好的设备添加的已绑定list集合  
                                bondDevices.add(unbondDevices.get(arg2));  
                                // 将绑定好的设备从未绑定list集合中移除  
                                unbondDevices.remove(arg2);  
                                addBondDevicesToListView();  
                                addUnbondDevicesToListView();  
                            } catch (Exception e) {  
                                Toast.makeText(context, "配对失败!", Toast.LENGTH_SHORT)  
                                        .show();  
                            }  
      
                        }  
                    });  
        }  
      
        public BluetoothService(Context context, ListView unbondDevicesListView,  
                ListView bondDevicesListView, Button switchBT, Button searchDevices) {  
            this.context = context;  
            this.unbondDevicesListView = unbondDevicesListView;  
            this.bondDevicesListView = bondDevicesListView;  
            // this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
            this.unbondDevices = new ArrayList<BluetoothDevice>();  
            this.bondDevices = new ArrayList<BluetoothDevice>();  
            this.switchBT = switchBT;  
            this.searchDevices = searchDevices;  
            this.initIntentFilter();  
      
        }  
      
        private void initIntentFilter() {  
            // 设置广播信息过滤  
            IntentFilter intentFilter = new IntentFilter();  
            intentFilter.addAction(BluetoothDevice.ACTION_FOUND);  
            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);  
            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
            intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);  
            // 注册广播接收器,接收并处理搜索结果  
            context.registerReceiver(receiver, intentFilter);  
      
        }  
      
        /** 
         * 打开蓝牙 
         */  
        public void openBluetooth(Activity activity) {  
            Intent enableBtIntent = new Intent(  
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);  
            activity.startActivityForResult(enableBtIntent, 1);  
      
        }  
      
        /** 
         * 关闭蓝牙 
         */  
        public void closeBluetooth() {  
            this.bluetoothAdapter.disable();  
        }  
      
        /** 
         * 判断蓝牙是否打开 
         *  
         * @return boolean 
         */  
        public boolean isOpen() {  
            return this.bluetoothAdapter.isEnabled();  
      
        }  
      
        /** 
         * 搜索蓝牙设备 
         */  
        public void searchDevices() {  
            this.bondDevices.clear();  
            this.unbondDevices.clear();  
      
            // 寻找蓝牙设备,android会将查找到的设备以广播形式发出去  
            this.bluetoothAdapter.startDiscovery();  
        }  
      
        /** 
         * 添加未绑定蓝牙设备到list集合 
         *  
         * @param device 
         */  
        public void addUnbondDevices(BluetoothDevice device) {  
            System.out.println("未绑定设备名称:" + device.getName());  
            if (!this.unbondDevices.contains(device)) {  
                this.unbondDevices.add(device);  
            }  
        }  
      
        /** 
         * 添加已绑定蓝牙设备到list集合 
         *  
         * @param device 
         */  
        public void addBandDevices(BluetoothDevice device) {  
            System.out.println("已绑定设备名称:" + device.getName());  
            if (!this.bondDevices.contains(device)) {  
                this.bondDevices.add(device);  
            }  
        }  
      
        /** 
         * 蓝牙广播接收器 
         */  
        private BroadcastReceiver receiver = new BroadcastReceiver() {  
      
            ProgressDialog progressDialog = null;  
      
            @Override  
            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) {  
                        addBandDevices(device);  
                    } else {  
                        addUnbondDevices(device);  
                    }  
                } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {  
                    progressDialog = ProgressDialog.show(context, "请稍等...",  
                            "搜索蓝牙设备中...", true);  
      
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED  
                        .equals(action)) {  
                    System.out.println("设备搜索完毕");  
                    progressDialog.dismiss();  
      
                    addUnbondDevicesToListView();  
                    addBondDevicesToListView();  
                    // bluetoothAdapter.cancelDiscovery();  
                }  
                if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {  
                    if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {  
                        System.out.println("--------打开蓝牙-----------");  
                        switchBT.setText("关闭蓝牙");  
                        searchDevices.setEnabled(true);  
                        bondDevicesListView.setEnabled(true);  
                        unbondDevicesListView.setEnabled(true);  
                    } else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {  
                        System.out.println("--------关闭蓝牙-----------");  
                        switchBT.setText("打开蓝牙");  
                        searchDevices.setEnabled(false);  
                        bondDevicesListView.setEnabled(false);  
                        unbondDevicesListView.setEnabled(false);  
                    }  
                }  
      
            }  
      
        };  
      
    }

    到这里,第一个界面的代码就写完了,当我们点击要打印的蓝牙设备时就会跳转到打印页面,跳转代码在BluetoothService.java的addBondDevicesToListView()中

    接下来让我们来看看第二个界面的代码,结构和第一个界面的代码一样,分类三个类,请看代码。。。。。


    PrintDataActivity.java


    public class PrintDataActivity extends Activity {  
        private Context context = null;  
      
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            this.setTitle("蓝牙打印");  
            this.setContentView(R.layout.printdata_layout);  
            this.context = this;  
            this.initListener();  
        }  
      
        /** 
         * 获得从上一个Activity传来的蓝牙地址 
         * @return String 
         */  
        private String getDeviceAddress() {  
            // 直接通过Context类的getIntent()即可获取Intent  
            Intent intent = this.getIntent();  
            // 判断  
            if (intent != null) {  
                return intent.getStringExtra("deviceAddress");  
            } else {  
                return null;  
            }  
        }  
      
        private void initListener() {  
            TextView deviceName = (TextView) this.findViewById(R.id.device_name);  
            TextView connectState = (TextView) this  
                    .findViewById(R.id.connect_state);  
      
            PrintDataAction printDataAction = new PrintDataAction(this.context,  
                    this.getDeviceAddress(), deviceName, connectState);  
      
            EditText printData = (EditText) this.findViewById(R.id.print_data);  
            Button send = (Button) this.findViewById(R.id.send);  
            Button command = (Button) this.findViewById(R.id.command);  
            printDataAction.setPrintData(printData);  
      
            send.setOnClickListener(printDataAction);  
            command.setOnClickListener(printDataAction);  
        }  
      
          
        @Override  
        protected void onDestroy() {  
            PrintDataService.disconnect();  
            super.onDestroy();  
        }  
          
    }

    PrintDataAction.java


    public class PrintDataAction implements OnClickListener {  
        private Context context = null;  
        private TextView deviceName = null;  
        private TextView connectState = null;  
        private EditText printData = null;  
        private String deviceAddress = null;  
        private PrintDataService printDataService = null;  
      
        public PrintDataAction(Context context, String deviceAddress,  
                TextView deviceName, TextView connectState) {  
            super();  
            this.context = context;  
            this.deviceAddress = deviceAddress;  
            this.deviceName = deviceName;  
            this.connectState = connectState;  
            this.printDataService = new PrintDataService(this.context,  
                    this.deviceAddress);  
            this.initView();  
      
        }  
      
        private void initView() {  
            // 设置当前设备名称  
            this.deviceName.setText(this.printDataService.getDeviceName());  
            // 一上来就先连接蓝牙设备  
            boolean flag = this.printDataService.connect();  
            if (flag == false) {  
                // 连接失败  
                this.connectState.setText("连接失败!");  
            } else {  
                // 连接成功  
                this.connectState.setText("连接成功!");  
      
            }  
        }  
      
        public void setPrintData(EditText printData) {  
            this.printData = printData;  
        }  
      
        @Override  
        public void onClick(View v) {  
            if (v.getId() == R.id.send) {  
                String sendData = this.printData.getText().toString();  
                this.printDataService.send(sendData + "\n");  
            } else if (v.getId() == R.id.command) {  
                this.printDataService.selectCommand();  
      
            }  
        }  
    }

    PrintDataService.java


    public class PrintDataService {  
        private Context context = null;  
        private String deviceAddress = null;  
        private BluetoothAdapter bluetoothAdapter = BluetoothAdapter  
                .getDefaultAdapter();  
        private BluetoothDevice device = null;  
        private static BluetoothSocket bluetoothSocket = null;  
        private static OutputStream outputStream = null;  
        private static final UUID uuid = UUID  
                .fromString("00001101-0000-1000-8000-00805F9B34FB");  
        private boolean isConnection = false;  
        final String[] items = { "复位打印机", "标准ASCII字体", "压缩ASCII字体", "字体不放大",  
                "宽高加倍", "取消加粗模式", "选择加粗模式", "取消倒置打印", "选择倒置打印", "取消黑白反显", "选择黑白反显",  
                "取消顺时针旋转90°", "选择顺时针旋转90°" };  
        final byte[][] byteCommands = { { 0x1b, 0x40 },// 复位打印机  
                { 0x1b, 0x4d, 0x00 },// 标准ASCII字体  
                { 0x1b, 0x4d, 0x01 },// 压缩ASCII字体  
                { 0x1d, 0x21, 0x00 },// 字体不放大  
                { 0x1d, 0x21, 0x11 },// 宽高加倍  
                { 0x1b, 0x45, 0x00 },// 取消加粗模式  
                { 0x1b, 0x45, 0x01 },// 选择加粗模式  
                { 0x1b, 0x7b, 0x00 },// 取消倒置打印  
                { 0x1b, 0x7b, 0x01 },// 选择倒置打印  
                { 0x1d, 0x42, 0x00 },// 取消黑白反显  
                { 0x1d, 0x42, 0x01 },// 选择黑白反显  
                { 0x1b, 0x56, 0x00 },// 取消顺时针旋转90°  
                { 0x1b, 0x56, 0x01 },// 选择顺时针旋转90°  
        };  
      
        public PrintDataService(Context context, String deviceAddress) {  
            super();  
            this.context = context;  
            this.deviceAddress = deviceAddress;  
            this.device = this.bluetoothAdapter.getRemoteDevice(this.deviceAddress);  
        }  
      
        /** 
         * 获取设备名称 
         *  
         * @return String 
         */  
        public String getDeviceName() {  
            return this.device.getName();  
        }  
      
        /** 
         * 连接蓝牙设备 
         */  
        public boolean connect() {  
            if (!this.isConnection) {  
                try {  
                    bluetoothSocket = this.device  
                            .createRfcommSocketToServiceRecord(uuid);  
                    bluetoothSocket.connect();  
                    outputStream = bluetoothSocket.getOutputStream();  
                    this.isConnection = true;  
                    if (this.bluetoothAdapter.isDiscovering()) {  
                        System.out.println("关闭适配器!");  
                        this.bluetoothAdapter.isDiscovering();  
                    }  
                } catch (Exception e) {  
                    Toast.makeText(this.context, "连接失败!", 1).show();  
                    return false;  
                }  
                Toast.makeText(this.context, this.device.getName() + "连接成功!",  
                        Toast.LENGTH_SHORT).show();  
                return true;  
            } else {  
                return true;  
            }  
        }  
      
        /** 
         * 断开蓝牙设备连接 
         */  
        public static void disconnect() {  
            System.out.println("断开蓝牙设备连接");  
            try {  
                bluetoothSocket.close();  
                outputStream.close();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
      
        }  
      
        /** 
         * 选择指令 
         */  
        public void selectCommand() {  
            new AlertDialog.Builder(context).setTitle("请选择指令")  
                    .setItems(items, new DialogInterface.OnClickListener() {  
                        @Override  
                        public void onClick(DialogInterface dialog, int which) {  
                            try {  
                                outputStream.write(byteCommands[which]);  
                            } catch (IOException e) {  
                                Toast.makeText(context, "设置指令失败!",  
                                        Toast.LENGTH_SHORT).show();  
                            }  
                        }  
                    }).create().show();  
        }  
      
        /** 
         * 发送数据 
         */  
        public void send(String sendData) {  
            if (this.isConnection) {  
                System.out.println("开始打印!!");  
                try {  
                    byte[] data = sendData.getBytes("gbk");  
                    outputStream.write(data, 0, data.length);  
                    outputStream.flush();  
                } catch (IOException e) {  
                    Toast.makeText(this.context, "发送失败!", Toast.LENGTH_SHORT)  
                            .show();  
                }  
            } else {  
                Toast.makeText(this.context, "设备未连接,请重新连接!", Toast.LENGTH_SHORT)  
                        .show();  
      
            }  
        }  
      
    }

    羡慕羡慕羡慕羡慕到此,全部代码贴完,也就大功告成了羡慕羡慕羡慕羡慕

    对了对了,差点忘记一件很重要的事情!!清单文件忘记给权限啦!!

    权限

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

    注册Activity

    <activity android:name=".BluetoothActivity" />  
    <activity android:name=".PrintDataActivity" />  
    
    

    得意这下子就真的搞定了!

    展开全文
  • 最近在做一个安卓应用,其中一个需求是要求用蓝牙连接打印机实现打印功能。一开始没有一点头绪,网上找了很多资料也找不到有用数据。所以自己就去研究,最终,功夫不负有心人,顺利完成了这个功能。下边贴出我...

    本文转载至:http://blog.csdn.net/reality_jie_blog/article/details/11895843

    最近在做一个安卓应用,其中有一个需求是要求用蓝牙连接打印机实现打印功能。一开始没有一点头绪,网上找了很多资料也找不到有用的数据。所以自己就去研究,最终,功夫不负有心人,顺利的完成了这个功能。下边贴出我写的代码,共有需要的IT哥们参考学习。

    完整源码下载

    我们先看看运行效果图吧。。。

    1.这是主界面的效果图


    贴上布局文件的代码:bluetooth_layout.xml

    [html] view plaincopy
    1. <span style="font-size:12px"><?xml version="1.0" encoding="utf-8"?>  
    2. <RelativeLayout  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="match_parent" >  
    5.   
    6.     <Button  
    7.         android:id="@+id/openBluetooth_tb"  
    8.         android:layout_width="130dp"  
    9.         android:layout_height="wrap_content"  
    10.         android:layout_alignParentRight="true"  
    11.         android:layout_marginRight="18dp"  
    12.         android:layout_marginTop="5dp"  
    13.         android:text="打开蓝牙" />  
    14.   
    15.     <Button  
    16.         android:id="@+id/searchDevices"  
    17.         android:layout_width="match_parent"  
    18.         android:layout_height="wrap_content"  
    19.         android:layout_alignParentLeft="true"  
    20.         android:layout_below="@+id/openBluetooth_tb"  
    21.         android:layout_marginTop="20dp"  
    22.         android:text="搜索设备" />  
    23.   
    24.     <View  
    25.         android:layout_width="match_parent"  
    26.         android:layout_height="3dp"  
    27.         android:layout_alignParentLeft="true"  
    28.         android:layout_below="@+id/searchDevices"  
    29.         android:background="@android:color/darker_gray" />  
    30.   
    31.     <LinearLayout  
    32.         android:id="@+id/linearLayout1"  
    33.         android:layout_width="match_parent"  
    34.         android:layout_height="150dp"  
    35.         android:layout_marginTop="125dp"  
    36.         android:orientation="vertical" >  
    37.   
    38.         <TextView  
    39.             android:layout_width="match_parent"  
    40.             android:layout_height="wrap_content"  
    41.             android:text="未配对设备" />  
    42.   
    43.         <ListView  
    44.             android:id="@+id/unbondDevices"  
    45.             android:layout_width="wrap_content"  
    46.             android:layout_height="wrap_content" />  
    47.     </LinearLayout>  
    48.   
    49.     <View  
    50.         android:layout_width="match_parent"  
    51.         android:layout_height="3dp"  
    52.         android:layout_alignParentLeft="true"  
    53.         android:layout_below="@+id/searchDevices"  
    54.         android:layout_marginTop="160dp"  
    55.         android:background="@android:color/darker_gray" />  
    56.   
    57.     <LinearLayout  
    58.         android:layout_width="match_parent"  
    59.         android:layout_height="190dp"  
    60.         android:layout_marginTop="288dp"  
    61.         android:orientation="vertical" >  
    62.   
    63.         <TextView  
    64.             android:layout_width="match_parent"  
    65.             android:layout_height="wrap_content"  
    66.             android:text="已配对设备" />  
    67.           <ListView  
    68.             android:id="@+id/bondDevices"  
    69.             android:layout_width="wrap_content"  
    70.            android:layout_height="wrap_content"  
    71.            android:layout_alignParentLeft="true"  
    72.            android:layout_below="@+id/linearLayout1" >  
    73.          </ListView>  
    74.     </LinearLayout>  
    75.   
    76.     <Button  
    77.         android:id="@+id/return_Bluetooth_btn"  
    78.         android:layout_width="100dp"  
    79.         android:layout_height="wrap_content"  
    80.         android:layout_above="@+id/searchDevices"  
    81.         android:layout_alignParentLeft="true"  
    82.         android:text="返回" />  
    83.   
    84. </RelativeLayout></span>  


    从上边的布局文件中不难看出,其中有两个ListView,OK,那下边贴出对应的两个item布局文件

      --> 第一个item:unbonddevice_item.xml

    [html] view plaincopy
    1. <span style="font-size:14px"><?xml version="1.0" encoding="utf-8"?>    
    2. <RelativeLayout  
    3.     android:layout_width="match_parent"    
    4.     android:layout_height="match_parent" >    
    5.     
    6.     <TextView    
    7.         android:id="@+id/device_name"    
    8.         android:layout_width="match_parent"    
    9.         android:layout_height="wrap_content"    
    10.         android:layout_alignParentLeft="true"    
    11.         android:layout_alignParentTop="true"    
    12.         android:text="未绑定设备"    
    13.         android:textAppearance="?android:attr/textAppearanceLarge" />    
    14.     
    15. </RelativeLayout></span>  

    -->第二个item:bonddevice_item.xml

    [html] view plaincopy
    1. <span style="font-size:14px"><?xml version="1.0" encoding="utf-8"?>    
    2. <RelativeLayout  
    3.     android:layout_width="match_parent"    
    4.     android:layout_height="match_parent" >    
    5.     
    6.     <TextView    
    7.         android:id="@+id/device_name"    
    8.         android:layout_width="match_parent"    
    9.         android:layout_height="wrap_content"    
    10.         android:layout_alignParentLeft="true"    
    11.         android:layout_alignParentTop="true"    
    12.         android:text="已绑定设备"    
    13.         android:textAppearance="?android:attr/textAppearanceLarge" />    
    14.     
    15. </RelativeLayout></span>  

    2.还有另外一个布局文件,就是当点击已绑定蓝牙设备下边的某个item时进入打印的界面,不多说,看图!



    代码如下:printdata_layout.xml

    [html] view plaincopy
    1. <?xml version="1.0" encoding="utf-8"?>    
    2. <RelativeLayout    
    3.     android:layout_width="match_parent"    
    4.     android:layout_height="match_parent" >    
    5.     
    6.     <EditText    
    7.         android:id="@+id/print_data"    
    8.         android:layout_width="match_parent"    
    9.         android:layout_height="200dp"    
    10.         android:layout_alignParentLeft="true"    
    11.         android:layout_alignParentTop="true"    
    12.         android:layout_marginTop="46dp" >    
    13.     </EditText>    
    14.     
    15.     <TextView    
    16.         android:id="@+id/device_name"    
    17.         android:layout_width="wrap_content"    
    18.         android:layout_height="wrap_content"    
    19.         android:layout_alignParentLeft="true"    
    20.         android:layout_alignParentTop="true"    
    21.         android:layout_marginTop="16dp"    
    22.         android:text="Large Text"    
    23.         android:textAppearance="?android:attr/textAppearanceLarge" />    
    24.     
    25.     <TextView    
    26.         android:id="@+id/connect_state"    
    27.         android:layout_width="wrap_content"    
    28.         android:layout_height="wrap_content"    
    29.         android:layout_alignBaseline="@+id/device_name"    
    30.         android:layout_alignBottom="@+id/device_name"    
    31.         android:layout_marginLeft="42dp"    
    32.         android:layout_toRightOf="@+id/device_name"    
    33.         android:text="Large Text"    
    34.         android:textAppearance="?android:attr/textAppearanceLarge" />    
    35.     
    36.     <Button    
    37.         android:id="@+id/send"    
    38.         android:layout_width="match_parent"    
    39.         android:layout_height="wrap_content"    
    40.         android:layout_alignParentLeft="true"    
    41.         android:layout_below="@+id/print_data"    
    42.         android:layout_marginTop="21dp"    
    43.         android:text="打印" />    
    44.     
    45.     <Button    
    46.         android:id="@+id/command"    
    47.         android:layout_width="match_parent"    
    48.         android:layout_height="wrap_content"    
    49.         android:layout_alignParentLeft="true"    
    50.         android:layout_below="@+id/send"    
    51.         android:text="指令" />    
    52.         
    53. </RelativeLayout>  

    至此,布局文件就搞定了,接下来就要编写java代码了。主要有一下这么几个类,一个一个来哈

    BluetoothActivity.java

    这个类的主要作用是初始化主界面,看代码

    [java] view plaincopy
    1. public class BluetoothActivity extends Activity {    
    2.     private Context context = null;    
    3.     
    4.     public void onCreate(Bundle savedInstanceState) {    
    5.         super.onCreate(savedInstanceState);    
    6.         this.context = this;    
    7.         setTitle("蓝牙打印");    
    8.         setContentView(R.layout.bluetooth_layout);    
    9.         this.initListener();    
    10.     }    
    11.     
    12.     private void initListener() {    
    13.         ListView unbondDevices = (ListView) this    
    14.                 .findViewById(R.id.unbondDevices);    
    15.         ListView bondDevices = (ListView) this.findViewById(R.id.bondDevices);    
    16.         Button switchBT = (Button) this.findViewById(R.id.openBluetooth_tb);    
    17.         Button searchDevices = (Button) this.findViewById(R.id.searchDevices);    
    18.     
    19.         BluetoothAction bluetoothAction = new BluetoothAction(this.context,    
    20.                 unbondDevices, bondDevices, switchBT, searchDevices,    
    21.                 BluetoothActivity.this);    
    22.     
    23.         Button returnButton = (Button) this    
    24.                 .findViewById(R.id.return_Bluetooth_btn);    
    25.         bluetoothAction.setSearchDevices(searchDevices);    
    26.         bluetoothAction.initView();    
    27.     
    28.         switchBT.setOnClickListener(bluetoothAction);    
    29.         searchDevices.setOnClickListener(bluetoothAction);    
    30.         returnButton.setOnClickListener(bluetoothAction);    
    31.     }    
    32.     //屏蔽返回键的代码:    
    33.     public boolean onKeyDown(int keyCode,KeyEvent event)    
    34.     {    
    35.         switch(keyCode)    
    36.         {    
    37.             case KeyEvent.KEYCODE_BACK:return true;    
    38.         }    
    39.         return super.onKeyDown(keyCode, event);    
    40.     }    
    41. }  

    BluetoothAction.java

    这个类顾名思义,是处理bluetoothActivity中各种操作事件的action类,看代码


    [java] view plaincopy
    1. <span style="font-size:14px">public class BluetoothAction implements OnClickListener {    
    2.     
    3.     private Button switchBT = null;    
    4.     private Button searchDevices = null;    
    5.     private Activity activity = null;    
    6.     
    7.     private ListView unbondDevices = null;    
    8.     private ListView bondDevices = null;    
    9.     private Context context = null;    
    10.     private BluetoothService bluetoothService = null;    
    11.     
    12.     public BluetoothAction(Context context, ListView unbondDevices,    
    13.             ListView bondDevices, Button switchBT, Button searchDevices,    
    14.             Activity activity) {    
    15.         super();    
    16.         this.context = context;    
    17.         this.unbondDevices = unbondDevices;    
    18.         this.bondDevices = bondDevices;    
    19.         this.switchBT = switchBT;    
    20.         this.searchDevices = searchDevices;    
    21.         this.activity = activity;    
    22.         this.bluetoothService = new BluetoothService(this.context,    
    23.                 this.unbondDevices, this.bondDevices, this.switchBT,    
    24.                 this.searchDevices);    
    25.     }    
    26.     
    27.     public void setSwitchBT(Button switchBT) {    
    28.         this.switchBT = switchBT;    
    29.     }    
    30.     
    31.     public void setSearchDevices(Button searchDevices) {    
    32.         this.searchDevices = searchDevices;    
    33.     }    
    34.     
    35.     public void setUnbondDevices(ListView unbondDevices) {    
    36.         this.unbondDevices = unbondDevices;    
    37.     }    
    38.     
    39.     /**  
    40.      * 初始化界面  
    41.      */    
    42.     public void initView() {    
    43.     
    44.         if (this.bluetoothService.isOpen()) {    
    45.             System.out.println("蓝牙有开!");    
    46.             switchBT.setText("关闭蓝牙");    
    47.         }    
    48.         if (!this.bluetoothService.isOpen()) {    
    49.             System.out.println("蓝牙没开!");    
    50.             this.searchDevices.setEnabled(false);    
    51.         }    
    52.     }    
    53.     
    54.     private void searchDevices() {    
    55.         bluetoothService.searchDevices();    
    56.     }    
    57.     
    58.     /**  
    59.      * 各种按钮的监听  
    60.      */    
    61.     @Override    
    62.     public void onClick(View v) {    
    63.         if (v.getId() == R.id.searchDevices) {    
    64.             this.searchDevices();    
    65.         } else if (v.getId() == R.id.return_Bluetooth_btn) {    
    66.             activity.finish();    
    67.         } else if (v.getId() == R.id.openBluetooth_tb) {    
    68.             if (!this.bluetoothService.isOpen()) {    
    69.                 // 蓝牙关闭的情况    
    70.                 System.out.println("蓝牙关闭的情况");    
    71.                 this.bluetoothService.openBluetooth(activity);    
    72.             } else {    
    73.                 // 蓝牙打开的情况    
    74.                 System.out.println("蓝牙打开的情况");    
    75.                 this.bluetoothService.closeBluetooth();    
    76.     
    77.             }    
    78.     
    79.         }    
    80.     }    
    81.     
    82. }</span>  



    这个类会把各种请求动作分门别类,交给BluetoothService.java来处理,看代码


    [java] view plaincopy
    1. public class BluetoothService {    
    2.     private Context context = null;    
    3.     private BluetoothAdapter bluetoothAdapter = BluetoothAdapter    
    4.             .getDefaultAdapter();    
    5.     private ArrayList<BluetoothDevice> unbondDevices = null// 用于存放未配对蓝牙设备    
    6.     private ArrayList<BluetoothDevice> bondDevices = null;// 用于存放已配对蓝牙设备    
    7.     private Button switchBT = null;    
    8.     private Button searchDevices = null;    
    9.     private ListView unbondDevicesListView = null;    
    10.     private ListView bondDevicesListView = null;    
    11.     
    12.     /**  
    13.      * 添加已绑定蓝牙设备到ListView  
    14.      */    
    15.     private void addBondDevicesToListView() {    
    16.         ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();    
    17.         int count = this.bondDevices.size();    
    18.         System.out.println("已绑定设备数量:" + count);    
    19.         for (int i = 0; i < count; i++) {    
    20.             HashMap<String, Object> map = new HashMap<String, Object>();    
    21.             map.put("deviceName"this.bondDevices.get(i).getName());    
    22.             data.add(map);// 把item项的数据加到data中    
    23.         }    
    24.         String[] from = { "deviceName" };    
    25.         int[] to = { R.id.device_name };    
    26.         SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data,    
    27.                 R.layout.bonddevice_item, from, to);    
    28.         // 把适配器装载到listView中    
    29.         this.bondDevicesListView.setAdapter(simpleAdapter);    
    30.     
    31.         this.bondDevicesListView    
    32.                 .setOnItemClickListener(new OnItemClickListener() {    
    33.     
    34.                     @Override    
    35.                     public void onItemClick(AdapterView<?> arg0, View arg1,    
    36.                             int arg2, long arg3) {    
    37.                         BluetoothDevice device = bondDevices.get(arg2);    
    38.                         Intent intent = new Intent();    
    39.                         intent.setClassName(context,    
    40.                                 "com.lifeng.jdxt.view.PrintDataActivity");    
    41.                         intent.putExtra("deviceAddress", device.getAddress());    
    42.                         context.startActivity(intent);    
    43.                     }    
    44.                 });    
    45.     
    46.     }    
    47.     
    48.     /**  
    49.      * 添加未绑定蓝牙设备到ListView  
    50.      */    
    51.     private void addUnbondDevicesToListView() {    
    52.         ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();    
    53.         int count = this.unbondDevices.size();    
    54.         System.out.println("未绑定设备数量:" + count);    
    55.         for (int i = 0; i < count; i++) {    
    56.             HashMap<String, Object> map = new HashMap<String, Object>();    
    57.             map.put("deviceName"this.unbondDevices.get(i).getName());    
    58.             data.add(map);// 把item项的数据加到data中    
    59.         }    
    60.         String[] from = { "deviceName" };    
    61.         int[] to = { R.id.device_name };    
    62.         SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data,    
    63.                 R.layout.unbonddevice_item, from, to);    
    64.     
    65.         // 把适配器装载到listView中    
    66.         this.unbondDevicesListView.setAdapter(simpleAdapter);    
    67.     
    68.         // 为每个item绑定监听,用于设备间的配对    
    69.         this.unbondDevicesListView    
    70.                 .setOnItemClickListener(new OnItemClickListener() {    
    71.     
    72.                     @Override    
    73.                     public void onItemClick(AdapterView<?> arg0, View arg1,    
    74.                             int arg2, long arg3) {    
    75.                         try {    
    76.                             Method createBondMethod = BluetoothDevice.class    
    77.                                     .getMethod("createBond");    
    78.                             createBondMethod    
    79.                                     .invoke(unbondDevices.get(arg2));    
    80.                             // 将绑定好的设备添加的已绑定list集合    
    81.                             bondDevices.add(unbondDevices.get(arg2));    
    82.                             // 将绑定好的设备从未绑定list集合中移除    
    83.                             unbondDevices.remove(arg2);    
    84.                             addBondDevicesToListView();    
    85.                             addUnbondDevicesToListView();    
    86.                         } catch (Exception e) {    
    87.                             Toast.makeText(context, "配对失败!", Toast.LENGTH_SHORT)    
    88.                                     .show();    
    89.                         }    
    90.     
    91.                     }    
    92.                 });    
    93.     }    
    94.     
    95.     public BluetoothService(Context context, ListView unbondDevicesListView,    
    96.             ListView bondDevicesListView, Button switchBT, Button searchDevices) {    
    97.         this.context = context;    
    98.         this.unbondDevicesListView = unbondDevicesListView;    
    99.         this.bondDevicesListView = bondDevicesListView;    
    100.         // this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
    101.         this.unbondDevices = new ArrayList<BluetoothDevice>();    
    102.         this.bondDevices = new ArrayList<BluetoothDevice>();    
    103.         this.switchBT = switchBT;    
    104.         this.searchDevices = searchDevices;    
    105.         this.initIntentFilter();    
    106.     
    107.     }    
    108.     
    109.     private void initIntentFilter() {    
    110.         // 设置广播信息过滤    
    111.         IntentFilter intentFilter = new IntentFilter();    
    112.         intentFilter.addAction(BluetoothDevice.ACTION_FOUND);    
    113.         intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);    
    114.         intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);    
    115.         intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);    
    116.         // 注册广播接收器,接收并处理搜索结果    
    117.         context.registerReceiver(receiver, intentFilter);    
    118.     
    119.     }    
    120.     
    121.     /**  
    122.      * 打开蓝牙  
    123.      */    
    124.     public void openBluetooth(Activity activity) {    
    125.         Intent enableBtIntent = new Intent(    
    126.                 BluetoothAdapter.ACTION_REQUEST_ENABLE);    
    127.         activity.startActivityForResult(enableBtIntent, 1);    
    128.     
    129.     }    
    130.     
    131.     /**  
    132.      * 关闭蓝牙  
    133.      */    
    134.     public void closeBluetooth() {    
    135.         this.bluetoothAdapter.disable();    
    136.     }    
    137.     
    138.     /**  
    139.      * 判断蓝牙是否打开  
    140.      *   
    141.      * @return boolean  
    142.      */    
    143.     public boolean isOpen() {    
    144.         return this.bluetoothAdapter.isEnabled();    
    145.     
    146.     }    
    147.     
    148.     /**  
    149.      * 搜索蓝牙设备  
    150.      */    
    151.     public void searchDevices() {    
    152.         this.bondDevices.clear();    
    153.         this.unbondDevices.clear();    
    154.     
    155.         // 寻找蓝牙设备,android会将查找到的设备以广播形式发出去    
    156.         this.bluetoothAdapter.startDiscovery();    
    157.     }    
    158.     
    159.     /**  
    160.      * 添加未绑定蓝牙设备到list集合  
    161.      *   
    162.      * @param device  
    163.      */    
    164.     public void addUnbondDevices(BluetoothDevice device) {    
    165.         System.out.println("未绑定设备名称:" + device.getName());    
    166.         if (!this.unbondDevices.contains(device)) {    
    167.             this.unbondDevices.add(device);    
    168.         }    
    169.     }    
    170.     
    171.     /**  
    172.      * 添加已绑定蓝牙设备到list集合  
    173.      *   
    174.      * @param device  
    175.      */    
    176.     public void addBandDevices(BluetoothDevice device) {    
    177.         System.out.println("已绑定设备名称:" + device.getName());    
    178.         if (!this.bondDevices.contains(device)) {    
    179.             this.bondDevices.add(device);    
    180.         }    
    181.     }    
    182.     
    183.     /**  
    184.      * 蓝牙广播接收器  
    185.      */    
    186.     private BroadcastReceiver receiver = new BroadcastReceiver() {    
    187.     
    188.         ProgressDialog progressDialog = null;    
    189.     
    190.         @Override    
    191.         public void onReceive(Context context, Intent intent) {    
    192.             String action = intent.getAction();    
    193.             if (BluetoothDevice.ACTION_FOUND.equals(action)) {    
    194.                 BluetoothDevice device = intent    
    195.                         .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);    
    196.                 if (device.getBondState() == BluetoothDevice.BOND_BONDED) {    
    197.                     addBandDevices(device);    
    198.                 } else {    
    199.                     addUnbondDevices(device);    
    200.                 }    
    201.             } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {    
    202.                 progressDialog = ProgressDialog.show(context, "请稍等...",    
    203.                         "搜索蓝牙设备中..."true);    
    204.     
    205.             } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED    
    206.                     .equals(action)) {    
    207.                 System.out.println("设备搜索完毕");    
    208.                 progressDialog.dismiss();    
    209.     
    210.                 addUnbondDevicesToListView();    
    211.                 addBondDevicesToListView();    
    212.                 // bluetoothAdapter.cancelDiscovery();    
    213.             }    
    214.             if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {    
    215.                 if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {    
    216.                     System.out.println("--------打开蓝牙-----------");    
    217.                     switchBT.setText("关闭蓝牙");    
    218.                     searchDevices.setEnabled(true);    
    219.                     bondDevicesListView.setEnabled(true);    
    220.                     unbondDevicesListView.setEnabled(true);    
    221.                 } else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {    
    222.                     System.out.println("--------关闭蓝牙-----------");    
    223.                     switchBT.setText("打开蓝牙");    
    224.                     searchDevices.setEnabled(false);    
    225.                     bondDevicesListView.setEnabled(false);    
    226.                     unbondDevicesListView.setEnabled(false);    
    227.                 }    
    228.             }    
    229.     
    230.         }    
    231.     
    232.     };    
    233.     
    234. }  

    到这里,第一个界面的代码就写完了,当我们点击要打印的蓝牙设备时就会跳转到打印页面,跳转代码在BluetoothService.java的addBondDevicesToListView()中

    接下来让我们来看看第二个界面的代码,结构和第一个界面的代码一样,分类三个类,请看代码。。。。。


    PrintDataActivity.java


    [java] view plaincopy
    1. public class PrintDataActivity extends Activity {    
    2.     private Context context = null;    
    3.     
    4.     public void onCreate(Bundle savedInstanceState) {    
    5.         super.onCreate(savedInstanceState);    
    6.         this.setTitle("蓝牙打印");    
    7.         this.setContentView(R.layout.printdata_layout);    
    8.         this.context = this;    
    9.         this.initListener();    
    10.     }    
    11.     
    12.     /**  
    13.      * 获得从上一个Activity传来的蓝牙地址  
    14.      * @return String  
    15.      */    
    16.     private String getDeviceAddress() {    
    17.         // 直接通过Context类的getIntent()即可获取Intent    
    18.         Intent intent = this.getIntent();    
    19.         // 判断    
    20.         if (intent != null) {    
    21.             return intent.getStringExtra("deviceAddress");    
    22.         } else {    
    23.             return null;    
    24.         }    
    25.     }    
    26.     
    27.     private void initListener() {    
    28.         TextView deviceName = (TextView) this.findViewById(R.id.device_name);    
    29.         TextView connectState = (TextView) this    
    30.                 .findViewById(R.id.connect_state);    
    31.     
    32.         PrintDataAction printDataAction = new PrintDataAction(this.context,    
    33.                 this.getDeviceAddress(), deviceName, connectState);    
    34.     
    35.         EditText printData = (EditText) this.findViewById(R.id.print_data);    
    36.         Button send = (Button) this.findViewById(R.id.send);    
    37.         Button command = (Button) this.findViewById(R.id.command);    
    38.         printDataAction.setPrintData(printData);    
    39.     
    40.         send.setOnClickListener(printDataAction);    
    41.         command.setOnClickListener(printDataAction);    
    42.     }    
    43.     
    44.         
    45.     @Override    
    46.     protected void onDestroy() {    
    47.         PrintDataService.disconnect();    
    48.         super.onDestroy();    
    49.     }    
    50.         
    51. }  

    PrintDataAction.java


    [java] view plaincopy
    1. <span style="font-size:14px">public class PrintDataAction implements OnClickListener {    
    2.     private Context context = null;    
    3.     private TextView deviceName = null;    
    4.     private TextView connectState = null;    
    5.     private EditText printData = null;    
    6.     private String deviceAddress = null;    
    7.     private PrintDataService printDataService = null;    
    8.     
    9.     public PrintDataAction(Context context, String deviceAddress,    
    10.             TextView deviceName, TextView connectState) {    
    11.         super();    
    12.         this.context = context;    
    13.         this.deviceAddress = deviceAddress;    
    14.         this.deviceName = deviceName;    
    15.         this.connectState = connectState;    
    16.         this.printDataService = new PrintDataService(this.context,    
    17.                 this.deviceAddress);    
    18.         this.initView();    
    19.     
    20.     }    
    21.     
    22.     private void initView() {    
    23.         // 设置当前设备名称    
    24.         this.deviceName.setText(this.printDataService.getDeviceName());    
    25.         // 一上来就先连接蓝牙设备    
    26.         boolean flag = this.printDataService.connect();    
    27.         if (flag == false) {    
    28.             // 连接失败    
    29.             this.connectState.setText("连接失败!");    
    30.         } else {    
    31.             // 连接成功    
    32.             this.connectState.setText("连接成功!");    
    33.     
    34.         }    
    35.     }    
    36.     
    37.     public void setPrintData(EditText printData) {    
    38.         this.printData = printData;    
    39.     }    
    40.     
    41.     @Override    
    42.     public void onClick(View v) {    
    43.         if (v.getId() == R.id.send) {    
    44.             String sendData = this.printData.getText().toString();    
    45.             this.printDataService.send(sendData + "\n");    
    46.         } else if (v.getId() == R.id.command) {    
    47.             this.printDataService.selectCommand();    
    48.     
    49.         }    
    50.     }    
    51. }</span>  

    PrintDataService.java


    [java] view plaincopy
    1. <span style="font-size:14px">public class PrintDataService {    
    2.     private Context context = null;    
    3.     private String deviceAddress = null;    
    4.     private BluetoothAdapter bluetoothAdapter = BluetoothAdapter    
    5.             .getDefaultAdapter();    
    6.     private BluetoothDevice device = null;    
    7.     private static BluetoothSocket bluetoothSocket = null;    
    8.     private static OutputStream outputStream = null;    
    9.     private static final UUID uuid = UUID    
    10.             .fromString("00001101-0000-1000-8000-00805F9B34FB");    
    11.     private boolean isConnection = false;    
    12.     final String[] items = { "复位打印机""标准ASCII字体""压缩ASCII字体""字体不放大",    
    13.             "宽高加倍""取消加粗模式""选择加粗模式""取消倒置打印""选择倒置打印""取消黑白反显""选择黑白反显",    
    14.             "取消顺时针旋转90°""选择顺时针旋转90°" };    
    15.     final byte[][] byteCommands = { { 0x1b0x40 },// 复位打印机    
    16.             { 0x1b0x4d0x00 },// 标准ASCII字体    
    17.             { 0x1b0x4d0x01 },// 压缩ASCII字体    
    18.             { 0x1d0x210x00 },// 字体不放大    
    19.             { 0x1d0x210x11 },// 宽高加倍    
    20.             { 0x1b0x450x00 },// 取消加粗模式    
    21.             { 0x1b0x450x01 },// 选择加粗模式    
    22.             { 0x1b0x7b0x00 },// 取消倒置打印    
    23.             { 0x1b0x7b0x01 },// 选择倒置打印    
    24.             { 0x1d0x420x00 },// 取消黑白反显    
    25.             { 0x1d0x420x01 },// 选择黑白反显    
    26.             { 0x1b0x560x00 },// 取消顺时针旋转90°    
    27.             { 0x1b0x560x01 },// 选择顺时针旋转90°    
    28.     };    
    29.     
    30.     public PrintDataService(Context context, String deviceAddress) {    
    31.         super();    
    32.         this.context = context;    
    33.         this.deviceAddress = deviceAddress;    
    34.         this.device = this.bluetoothAdapter.getRemoteDevice(this.deviceAddress);    
    35.     }    
    36.     
    37.     /**  
    38.      * 获取设备名称  
    39.      *   
    40.      * @return String  
    41.      */    
    42.     public String getDeviceName() {    
    43.         return this.device.getName();    
    44.     }    
    45.     
    46.     /**  
    47.      * 连接蓝牙设备  
    48.      */    
    49.     public boolean connect() {    
    50.         if (!this.isConnection) {    
    51.             try {    
    52.                 bluetoothSocket = this.device    
    53.                         .createRfcommSocketToServiceRecord(uuid);    
    54.                 bluetoothSocket.connect();    
    55.                 outputStream = bluetoothSocket.getOutputStream();    
    56.                 this.isConnection = true;    
    57.                 if (this.bluetoothAdapter.isDiscovering()) {    
    58.                     System.out.println("关闭适配器!");    
    59.                     this.bluetoothAdapter.isDiscovering();    
    60.                 }    
    61.             } catch (Exception e) {    
    62.                 Toast.makeText(this.context, "连接失败!"1).show();    
    63.                 return false;    
    64.             }    
    65.             Toast.makeText(this.context, this.device.getName() + "连接成功!",    
    66.                     Toast.LENGTH_SHORT).show();    
    67.             return true;    
    68.         } else {    
    69.             return true;    
    70.         }    
    71.     }    
    72.     
    73.     /**  
    74.      * 断开蓝牙设备连接  
    75.      */    
    76.     public static void disconnect() {    
    77.         System.out.println("断开蓝牙设备连接");    
    78.         try {    
    79.             bluetoothSocket.close();    
    80.             outputStream.close();    
    81.         } catch (IOException e) {    
    82.             // TODO Auto-generated catch block    
    83.             e.printStackTrace();    
    84.         }    
    85.     
    86.     }    
    87.     
    88.     /**  
    89.      * 选择指令  
    90.      */    
    91.     public void selectCommand() {    
    92.         new AlertDialog.Builder(context).setTitle("请选择指令")    
    93.                 .setItems(items, new DialogInterface.OnClickListener() {    
    94.                     @Override    
    95.                     public void onClick(DialogInterface dialog, int which) {    
    96.                         try {    
    97.                             outputStream.write(byteCommands[which]);    
    98.                         } catch (IOException e) {    
    99.                             Toast.makeText(context, "设置指令失败!",    
    100.                                     Toast.LENGTH_SHORT).show();    
    101.                         }    
    102.                     }    
    103.                 }).create().show();    
    104.     }    
    105.     
    106.     /**  
    107.      * 发送数据  
    108.      */    
    109.     public void send(String sendData) {    
    110.         if (this.isConnection) {    
    111.             System.out.println("开始打印!!");    
    112.             try {    
    113.                 byte[] data = sendData.getBytes("gbk");    
    114.                 outputStream.write(data, 0, data.length);    
    115.                 outputStream.flush();    
    116.             } catch (IOException e) {    
    117.                 Toast.makeText(this.context, "发送失败!", Toast.LENGTH_SHORT)    
    118.                         .show();    
    119.             }    
    120.         } else {    
    121.             Toast.makeText(this.context, "设备未连接,请重新连接!", Toast.LENGTH_SHORT)    
    122.                     .show();    
    123.     
    124.         }    
    125.     }    
    126.     
    127. }</span>  

    羡慕羡慕羡慕羡慕到此,全部代码贴完,也就大功告成了羡慕羡慕羡慕羡慕

    对了对了,差点忘记一件很重要的事情!!清单文件忘记给权限啦!!

    权限

    [html] view plaincopy
    1. <span style="font-size:14px"><uses-permission android:name="android.permission.BLUETOOTH" />    
    2.     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> </span>  

    注册Activity

    [html] view plaincopy
    1. <span style="font-size:14px"><activity android:name=".BluetoothActivity" />    
    2. <activity android:name=".PrintDataActivity" /> </span><span style="font-size:14px">   
    3.   
    4. </span>  

    得意这下子就真的搞定了!
    展开全文
  • 最近在做一个安卓应用,其中一个需求是要求用蓝牙连接打印机实现打印功能。一开始没有一点头绪,网上找了很多资料也找不到有用数据。所以自己就去研究,最终,功夫不负有心人,顺利完成了这个功能。下边贴出
  • 移动端Edge和Chrom浏览器能够调起打印功能页面,但是无法找到打印机。网络上打印机手机找不到,而且也无法安装对应驱动。 可蓝牙链接发票打印机,使用微信小程序,有的能搜索到设备,有的搜索不到设备,能...
  • android 安卓手机 网络打印 如果家WIFI共享打印机(不一定要带WIFI功能的打印机,可以通过WIFI路由器或WIFI共享器分配了IP地址的打印机),那你一定要下,手机直接打印输出,爽到底。
  • 实现手机与打印机相连接打印机基本条件简 介:安卓手机和苹果手机使用打印功能手机端需要下载扫描万能王APP才能使用,但此款APP支持打印机airPrint功能才行,但很多公司打印机不支持airprint手机打印功能,...
  • 打开方式:设置——辅助功能——开发者选项(假如你看不到开发者选项再想办法)——高级日志输出–点击允许全部华为手机也是不允许打印日志这个很奇葩。在这里可以看到原答案...
  • 主要介绍了Python实现竖排打印传单手机号码易撕条,代码非常简单,功能很实用,推荐给大家,需要小伙伴,参考下
  • 魅族手机默认是不开启打印高级日志。所以时候你使用一些自定义log库看不到输出日志。 打开方式:设置——辅助功能——开发者选项(假如你看不到开发者选项再想办法)——高级日志输出–点击允许全部 ...
  • 记录一下ionic3使用cordova插件连接TSC蓝牙热敏打印机打印功能,成品图展示: 引入cordova插件: cordova plugin add git://github.com/anilbhanushali/cordovaPluginTscPrinter 这个插件中默认引入的有TSC打印机...
  • 最近公司个需求实现手机端打印合同功能。上网搜索了一通,没靠谱。走一些歪门邪道调用第三方软件实现打印功能。这里选择对printershare下手。下载软件分析其中源码。看其中清单文件 ...
  • 需求中提到需要增加每一件商品可以打印,用于线下体验店实体商品二维码标签,客人可以根据手机扫二维码功能进行购买 任务描述: 1、如附件实现”批量打印标签“和单个商品”打印“标签功能。 2、标签两种”大...
  • 家里一台佳能MP288打印机,因为打印机太大在电脑桌上放不下,就想着把打印机放空闲大地方,利用路由器USB功能连接打印机,然后利用WIFI连接主路由共享打印给电脑和手机进行打印,进行。了这个想后前几天就在...
  • 富比士杂志(Forbes)资安记者Thomas Brewster日前与英国3D扫描打印业者Backface合作,利用3D打印出自己头像,并测试多款智能型手机的脸部解锁功能,结果所有Android手机全都被假头骗过,仅iPhone X成功挡住了。...
  • 企业面临泄密方式多种多样,除了通过常规U盘、移动硬盘、智能手机、打印机和网络渠道泄密,还可以通过手机拍照泄密,通过截图工具截图泄密,更甚者直接打印核心文档拿走泄密,对通过常规途径泄密行为,我们...
  • 首款3D打印赛车游戏,由智能手机驱动并兼容Arduino 游戏 与您朋友比赛(最多1000名玩家) 使用Android / Iphone应用程序或3D打印的遥控器进行驱动 观看实时计分板和圈速:每辆车都一个传感器,可以检测专门...
  • 初次看到这个东西,可能会误人为是移动硬盘或某人午餐盒,但实际上,这是一台PoGo3*4打印机,既然是打印机那就是用来打印的喽,可是...在以前这还是一个虽然很多手机但从来没人用内置功能,相信Android App...
  • 是用户实现快递单打印功能的好帮手。需要的朋友快来下载吧! 金码快递单打印软件特色功能 1、内置的快递单:顺丰速运、申通快递、圆通快递、中通快递、韵达快运、汇通快运、全一快递、EMS、天天快递、宅急送、...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 554
精华内容 221
关键字:

有打印功能的手机