Android蓝牙打印机

时间:2013-08-26 06:32:25

标签: android printing bluetooth android-bluetooth

我正在尝试制作一个Android蓝牙打印机应用程序,其中我成功检测到我附近的蓝牙设备,但是当其中一个设备选择连接时,我无法建立连接。另外,当我试图在列表视图中获取设备名称时,它会多次显示一个名称。我在下面发布我的代码。请帮助

  package com.example.test;

  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.util.List;
  import java.util.UUID;

  import android.os.Bundle;
  import android.os.Handler;
   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;
  import android.view.Menu;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.AdapterView;
  import android.widget.AdapterView.OnItemClickListener;
  import android.widget.ArrayAdapter;
  import android.widget.Button;
  import android.widget.ListView;
  import android.widget.TextView;
  import android.widget.Toast;

  public class MainActivity extends Activity  {

private static final int REQUEST_ENABLE_BT = 1;
OutputStream mmOutputStream;
  ListView listDevicesFound;
   Button btnScanDevice,connect;
  TextView stateBluetooth;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
List<String> discoverableDevicesList;

InputStream mmInputStream;
Thread workerThread;

byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;

  ArrayAdapter<String> btArrayAdapter;

  /** Called when the activity is first created. */
  @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btnScanDevice = (Button)findViewById(R.id.scandevice);

    stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    connect = (Button)findViewById(R.id.button2);
    listDevicesFound = (ListView)findViewById(R.id.devicesfound);
     btArrayAdapter = new ArrayAdapter<String>(this,       android.R.layout.simple_list_item_1);
    listDevicesFound.setAdapter(btArrayAdapter);


    CheckBlueToothState();

    btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);

    registerReceiver(ActionFoundReceiver, 
      new IntentFilter(BluetoothDevice.ACTION_FOUND));
}

 @Override
 protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(ActionFoundReceiver);
 }

 private void CheckBlueToothState(){
  if (mBluetoothAdapter == null){
     stateBluetooth.setText("Bluetooth NOT support");
    }else{
     if (mBluetoothAdapter.isEnabled()){
      if(mBluetoothAdapter.isDiscovering()){
       stateBluetooth.setText("Bluetooth is currently in device discovery process.");
      }else{
       stateBluetooth.setText("Bluetooth is Enabled.");
       btnScanDevice.setEnabled(true);
      }
     }else{
      stateBluetooth.setText("Bluetooth is NOT Enabled!");
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
     }
    }
}

private Button.OnClickListener btnScanDeviceOnClickListener
= new Button.OnClickListener(){

 @Override
 public void onClick(View arg0) {
 // TODO Auto-generated method stub
 btArrayAdapter.clear();
 mBluetoothAdapter.startDiscovery();
 }};

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // TODO Auto-generated method stub
    if(requestCode == REQUEST_ENABLE_BT){
    CheckBlueToothState();
  }
  }

  private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

  @Override
  public void onReceive(Context context, Intent intent) {
 // TODO Auto-generated method stub
 String action = intent.getAction();
 if(BluetoothDevice.ACTION_FOUND.equals(action)) {
         BluetoothDevice device =         intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
         btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
         btArrayAdapter.notifyDataSetChanged();
     }
   }

  };}

1 个答案:

答案 0 :(得分:1)

这是Dialog以显示ListView中的所有配对设备。

public  Dialog pushDevicePairDialog(){

            _mDeviceListView   = ((LayoutInflater) _mCallingActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.bluetooth_devices_list, null, false);
            _mDeviceListDialog = new Dialog(_mCallingActivity,R.style.ThemeDialogCustom);
            _mDeviceListDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            _mDeviceListDialog.setContentView(_mDeviceListView);
            _mDeviceListDialog.setCancelable(true);

            _mPairedDevicesArrayAdapter = new ArrayAdapter<String>(_mCallingActivity,R.layout.device_name);
            _mNewDevicesArrayAdapter    = new ArrayAdapter<String>(_mCallingActivity,R.layout.device_name);

            Button scanButton = (Button) _mDeviceListView.findViewById(R.id.button_scan);
            scanButton.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    doDiscovery();
                    v.setVisibility(View.GONE);
                }
            });

            ListView pairedListView = (ListView) _mDeviceListView.findViewById(R.id.paired_devices);
            pairedListView.setAdapter(_mPairedDevicesArrayAdapter);
            pairedListView.setOnItemClickListener(_mDeviceClickListener);

            ListView newDevicesListView = (ListView) _mDeviceListView.findViewById(R.id.new_devices);
            newDevicesListView.setAdapter(_mNewDevicesArrayAdapter);
            newDevicesListView.setOnItemClickListener(_mDeviceClickListener);

            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            _mCallingActivity.registerReceiver(_mReceiver, filter);

            filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            _mCallingActivity.registerReceiver(_mReceiver, filter);

            _mBtAdapter = BluetoothAdapter.getDefaultAdapter();

            Set<BluetoothDevice> pairedDevices = _mBtAdapter.getBondedDevices();

            if (pairedDevices.size() > 0) {
                _mDeviceListView.findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
                for (BluetoothDevice device : pairedDevices) {
                    String devName = device.getName();
                    if(devName != null && (devName.startsWith("ESYS") || devName.startsWith("ACC")))
                        _mPairedDevicesArrayAdapter.add(devName + "\n" + device.getAddress());
                }
            } else {
                String noDevices = _mCallingActivity.getResources().getText(R.string.none_paired).toString();
                _mPairedDevicesArrayAdapter.add(noDevices);
            }

            if (_mBluetoothService == null) 
                _mBluetoothService = new BluetoothConnectorService(_mCallingActivity);
                _mBluetoothService.setListener(this);
       return  _mDeviceListDialog;

    }