0

我正在尝试创建一个蓝牙打印机应用程序。现在我在手机和蓝牙打印机之间建立了一个简单的连接。我想要一些功能

  1. 每次都建立连接,当我点击打印按钮时。但我想在每次点击打印按钮后在初始阶段建立连接,它需要直接打印。
  2. 只显示配对设备的列表,但我也想显示附近的
    设备。

我正在尝试的是

 print.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (mBluetoothAdapter == null) {
                Toast.makeText(getContext(), "Message1", Toast.LENGTH_SHORT).show();
            } else {
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(
                            BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent,
                            REQUEST_ENABLE_BT);
                } else {
                    ListPairedDevices();
                    Intent connectIntent = new Intent(getContext(),
                            DeviceListActivity.class);
                    startActivityForResult(connectIntent,
                            REQUEST_CONNECT_DEVICE);
                }
            }
        }

    });
   public void onActivityResult(int mRequestCode, int mResultCode,
                             Intent mDataIntent) {
    super.onActivityResult(mRequestCode, mResultCode, mDataIntent);

    switch (mRequestCode) {
        case REQUEST_CONNECT_DEVICE:
            if (mResultCode == Activity.RESULT_OK) {
                Bundle mExtra = mDataIntent.getExtras();
                String mDeviceAddress = mExtra.getString("DeviceAddress");
                Log.v(TAG, "Coming incoming address " + mDeviceAddress);
                mBluetoothDevice = mBluetoothAdapter
                        .getRemoteDevice(mDeviceAddress);

                printCommand();
                // pairToDevice(mBluetoothDevice); This method is replaced by
                // progress dialog with thread
            }
            break;

        case REQUEST_ENABLE_BT:
            if (mResultCode == Activity.RESULT_OK) {
                ListPairedDevices();
                Intent connectIntent = new Intent(getContext(),
                        DeviceListActivity.class);
                startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
            } else {
                Toast.makeText(getContext(), "Message", Toast.LENGTH_SHORT).show();
            }
            break;
    }
}

  private void ListPairedDevices() {
    Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
            .getBondedDevices();
    if (mPairedDevices.size() > 0) {
        for (BluetoothDevice mDevice : mPairedDevices) {
            Log.v(TAG, "PairedDevices: " + mDevice.getName() + "  "
                    + mDevice.getAddress());
        }
    }
  }

   void printCommand(){
    try {
        mBluetoothSocket = mBluetoothDevice
                .createRfcommSocketToServiceRecord(applicationUUID);
        mBluetoothAdapter.cancelDiscovery();
        mBluetoothSocket.connect();
        // mHandler.sendEmptyMessage(0);
    } catch (IOException eConnectException) {
        Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
        closeSocket(mBluetoothSocket);
        return;
    }
    Thread t = new Thread() {
        public void run() {
            try {
                OutputStream os = mBluetoothSocket
                        .getOutputStream();
                String BILL = "";

                BILL = "                   Demo   \n";
                BILL = BILL
                        + "---------------------------------------------\n";
                BILL = BILL + String.format("%1$-5s %2$-14s %3$5s %4$5s 
         %5$8s", "s.No", "Product", "Rate","Qty", "Amount");
          os.write(BILL.getBytes());
                //This is printer specific code you can comment ==== > Start

                // Setting height
                int gs = 29;
                os.write(intToByteArray(gs));
                int h = 104;
                os.write(intToByteArray(h));
                int n = 162;
                os.write(intToByteArray(n));

                // Setting Width
                int gs_width = 29;
                os.write(intToByteArray(gs_width));
                int w = 119;
                os.write(intToByteArray(w));
                int n_width = 2;
                os.write(intToByteArray(n_width));


            } catch (Exception e) {
                Log.e("MainActivity", "Exe ", e);
            }
        }
    };
    t.start();
}
public static byte intToByteArray(int value) {
    byte[] b = ByteBuffer.allocate(4).putInt(value).array();

    for (int k = 0; k < b.length; k++) {
        System.out.println("Selva  [" + k + "] = " + "0x"
                + UnicodeFormatter.byteToHex(b[k]));
    }

    return b[3];
}

DeviceListActivity.Class 用于显示配对设备列表

 public class DeviceListActivity extends Activity {
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;

@Override
protected void onCreate(Bundle mSavedInstanceState) {
    super.onCreate(mSavedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.device_list);

    setResult(Activity.RESULT_CANCELED);
    mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, 
R.layout.device_name);

    ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
    mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
    mPairedListView.setOnItemClickListener(mDeviceClickListener);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();

    if (mPairedDevices.size() > 0) {
        findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
        for (BluetoothDevice mDevice : mPairedDevices) {
            mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
        }
    } else {
        String mNoDevices = "None Paired";//getResources().getText(R.string.none_paired).toString();
        mPairedDevicesArrayAdapter.add(mNoDevices);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (mBluetoothAdapter != null) {
        mBluetoothAdapter.cancelDiscovery();
    }
}

private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong) {

        try {
            mBluetoothAdapter.cancelDiscovery();
            String mDeviceInfo = ((TextView) mView).getText().toString();
            String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
            Log.v(TAG, "Device_Address " + mDeviceAddress);

            Bundle mBundle = new Bundle();
            mBundle.putString("DeviceAddress", mDeviceAddress);
            Intent mBackIntent = new Intent();
            mBackIntent.putExtras(mBundle);
            setResult(Activity.RESULT_OK, mBackIntent);
            finish();
        } catch (Exception ex) {

        }
    }
};

}

我有 android 的入门级知识。现在我需要您的支持来完成该应用程序。期待您的解决方案 编辑 1:在一个片段中建立蓝牙连接并在另一个片段中设置打印选项。我该怎么做,任何提供参考或示例会更有帮助

4

1 回答 1

0

好的,现在唯一的解决方案是连接蓝牙打印机并使用共享首选项保存......然后使用它......这样配对后它不会询问超过 1 次,您只需在移动设备中打开打印机和蓝牙并运行蓝牙输入Admin Mode

也给这个权限

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

您的代码是完美的,只需添加共享偏好并始终使用它。

于 2018-01-29T10:12:17.393 回答