1. 程式人生 > >Android開發之藍牙連接打印機

Android開發之藍牙連接打印機

cep sdi tco disable ner gis util receiver count

代碼很簡單,直接一個布局文件和一個activity。需要的朋友可以直接將這兩部分粘貼復制到項目中即可。

技術分享

Activity部分:

package com.anhua.bluetooth;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import com.example.imooc_weixinfragment.R;
import android.app.Activity; import android.app.ProgressDialog; 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; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter;
import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class BluetoothActivity extends Activity implements OnClickListener { private ListView unbondDevices = null; private ListView bondDevices = null; private Context context = null; private BluetoothAdapter bluetoothAdapter = BluetoothAdapter .getDefaultAdapter(); private ArrayList<BluetoothDevice> unbondDeviceslist = null; // 用於存放未配對藍牙設備 private ArrayList<BluetoothDevice> bondDeviceslist = null;// 用於存放已配對藍牙設備 private ListView unbondDevicesListView = null; private ListView bondDevicesListView = null; private Button searchDevices;// 搜索藍牙設備Button private TextView deviceName;// 藍牙設備的名字 private TextView connectState = null;//藍牙設備連接狀態 private String address;// 藍牙地址 private ImageView returnButton; private boolean isConnection = false; private BluetoothDevice devices = null; private static BluetoothSocket bluetoothSocket = null; private static final UUID uuid = UUID .fromString("00001101-0000-1000-8000-00805F9B34FB"); private static OutputStream outputStream = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.context = this; requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.bluetooth_layout); unbondDeviceslist = new ArrayList<BluetoothDevice>(); bondDeviceslist = new ArrayList<BluetoothDevice>(); this.initIntentFilter(); initView(); init(); } private void init() { deviceName=(TextView) findViewById(R.id.device_name); connectState=(TextView) findViewById(R.id.connect_state); unbondDevices = (ListView) this.findViewById(R.id.unbondDevices); bondDevices = (ListView) this.findViewById(R.id.bondDevices); searchDevices = (Button) this.findViewById(R.id.searchDevices); unbondDevicesListView = (ListView) findViewById(R.id.unbondDevices); bondDevicesListView = (ListView) findViewById(R.id.bondDevices); returnButton = (ImageView) this.findViewById(R.id.return_Bluetooth_btn); this.setSearchDevices(searchDevices); searchDevices.setOnClickListener(this); returnButton.setOnClickListener(this); } public void setSearchDevices(Button searchDevices) { this.searchDevices = searchDevices; } /** * 初始化界面 */ public void initView() { if (this.isOpen()) { System.out.println("藍牙有開!"); } if (!this.isOpen()) { System.out.println("藍牙沒開!"); this.searchDevices.setEnabled(false); } } @Override protected void onDestroy() { // TODO Auto-generated method stub this.disconnect(); super.onDestroy(); } /** * 添加已綁定藍牙設備到ListView */ private void addBondDevicesToListView() { ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); int count = this.bondDeviceslist.size(); System.out.println("已綁定設備數量:" + count); for (int i = 0; i < count; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("deviceName", this.bondDeviceslist.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) { deviceName.setVisibility(View.VISIBLE); connectState.setVisibility(View.VISIBLE); BluetoothDevice device = bondDeviceslist.get(arg2); address = device.getAddress();// 獲取藍牙地址 devices=bluetoothAdapter.getRemoteDevice(address); deviceName.setText(getDeviceName()); // 一上來就先連接藍牙設備 boolean flag = connect(); if (flag == false) { // 連接失敗 connectState.setText("連接失敗!"); } else { // 連接成功 connectState.setText("連接成功!"); } } }); } /** * 添加未綁定藍牙設備到ListView */ private void addUnbondDevicesToListView() { ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); int count = this.unbondDeviceslist.size(); System.out.println("未綁定設備數量:" + count); for (int i = 0; i < count; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("deviceName", this.unbondDeviceslist.get(i).getName()); data.add(map);// 把item項的數據加到data中 } String[] from = { "deviceName" }; int[] to = { R.id.undevice_name }; SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data, R.layout.unbonddevice_item, from, to); // 把適配器裝載到listView中 unbondDevicesListView.setAdapter(simpleAdapter); // 為每個item綁定監聽,用於設備間的配對 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(unbondDeviceslist.get(arg2)); // 將綁定好的設備添加的已綁定list集合 bondDeviceslist.add(unbondDeviceslist.get(arg2)); // 將綁定好的設備從未綁定list集合中移除 unbondDeviceslist.remove(arg2); addBondDevicesToListView(); addUnbondDevicesToListView(); } catch (Exception e) { Toast.makeText(context, "配對失敗!", Toast.LENGTH_SHORT).show(); } } }); } 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.bondDeviceslist.clear(); this.unbondDeviceslist.clear(); // 尋找藍牙設備,android會將查找到的設備以廣播形式發出去 this.bluetoothAdapter.startDiscovery(); } /** * 添加未綁定藍牙設備到list集合 * * @param device */ public void addUnbondDevices(BluetoothDevice device) { System.out.println("未綁定設備名稱:" + device.getName()); if (!this.unbondDeviceslist.contains(device)) { this.unbondDeviceslist.add(device); } } /** * 添加已綁定藍牙設備到list集合 * * @param device */ public void addBandDevices(BluetoothDevice device) { System.out.println("已綁定設備名稱:" + device.getName()); if (!this.bondDeviceslist.contains(device)) { this.bondDeviceslist.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(); } } }; /** * 獲取設備名稱 * * @return String */ public String getDeviceName() { return devices.getName(); } /** * 連接藍牙設備 */ public boolean connect() { if (!this.isConnection) { try { bluetoothSocket = this.devices .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.devices.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(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.searchDevices: this.searchDevices(); break; case R.id.return_Bluetooth_btn: finish(); break; default: break; } } }

布局文件部分:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/index"
    tools:context=".BluetoothActivity" >

    <LinearLayout
        android:id="@+id/openBluetooth_tb"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:background="#24cf5f"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/return_Bluetooth_btn"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:layout_gravity="center"
            android:layout_weight="5"
            android:src="@drawable/back"/>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="44dp"
            android:layout_weight="1"
            android:gravity="center"
            android:paddingRight="40dp"
            android:text="@string/titie_activity_conn_blue_list"
            android:textColor="#FFFFFF"
            android:textSize="30px" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/openBluetooth_tb"
        android:orientation="vertical" >

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

            <TextView
                android:visibility="gone"
                android:id="@+id/device_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="名稱"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:visibility="gone"
                android:id="@+id/connect_state"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="42dp"
                android:text="狀態"
                android:textAppearance="?android:attr/textAppearanceLarge" />
        </LinearLayout>

        <Button
            android:id="@+id/searchDevices"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            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: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:background="@android:color/darker_gray" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="190dp"
        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_below="@+id/linearLayout1" >
        </ListView>
    </LinearLayout>
    </LinearLayout>

</RelativeLayout>

通過以上兩部分就可以實現連接藍牙打印機的功能。

Android開發之藍牙連接打印機