android 連接藍牙打印機 BluetoothAdapter


android 連接藍牙打印機 BluetoothAdapter
  
源碼下載地址:https://github.com/yylxy/BluetoothText.git










public class PrintActivity extends AppCompatActivity {
//設備列表
private ListView listView;
    private ArrayList<PrintBean> mBluetoothDevicesDatas;
private PrintAdapter adapter;
//藍牙適配器
private BluetoothAdapter mBluetoothAdapter;
//請求的code
public static final int REQUEST_ENABLE_BT = 1;

private Switch mSwitch;
private FloatingActionButton mFloatingActionButton;
private ProgressBar mProgressBar;
private Toolbar toolbar;
private TextView searchHint;

/**
* 啟動打印頁面
*
* @param printContent 要打印的內容
*/
public static void starUi(Context context, String printContent) {
Intent intent = new Intent(context, PrintActivity.class);
intent.putExtra("id", id);
intent.putExtra("printContent", printContent);
context.startActivity(intent);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//廣播注冊
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
//初始化
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mSwitch = (Switch) findViewById(R.id.switch1);
mFloatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar3);
toolbar = (Toolbar) findViewById(R.id.toolbar);
searchHint = (TextView) findViewById(R.id.searchHint);
toolbar.setTitle("選擇打印設備");

listView = (ListView) findViewById(R.id.listView);
mBluetoothDevicesDatas = new ArrayList<>();
String printContent=getIntent().getStringExtra("printContent");
adapter = new PrintAdapter(this, mBluetoothDevicesDatas, TextUtils.isEmpty(printContent)?"123456789完\n\n\n":printContent);
listView.setAdapter(adapter);

chechBluetooth();
addViewListener();

}


/**
* 判斷有沒有開啟藍牙
*/
private void chechBluetooth() {
//沒有開啟藍牙
if (mBluetoothAdapter != null) {
if (!mBluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 設置藍牙可見性,最多300秒
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 20);
startActivityForResult(intent, REQUEST_ENABLE_BT);
setViewStatus(true);
//開啟藍牙
} else {
searchDevices();
setViewStatus(true);
mSwitch.setChecked(true);
}
}
}

/**
* 搜索狀態調整
*
* @param isSearch 是否開始搜索
*/
private void setViewStatus(boolean isSearch) {

if (isSearch) {
mFloatingActionButton.setVisibility(View.GONE);
searchHint.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
} else {
mFloatingActionButton.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
searchHint.setVisibility(View.GONE);
}
}


/**
* 添加View的監聽
*/
private void addViewListener() {
//藍牙的狀態
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
openBluetooth();
setViewStatus(true);
} else {
closeBluetooth();
}
}
});
//重新搜索
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mSwitch.isChecked()) {
searchDevices();
setViewStatus(true);
} else {
openBluetooth();
setViewStatus(true);
}
}
});

toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(PrintActivity.this, "88", Toast.LENGTH_SHORT).show();
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == REQUEST_ENABLE_BT) {
Log.e("text", "開啟藍牙");
searchDevices();
mSwitch.setChecked(true);
mBluetoothDevicesDatas.clear();
adapter.notifyDataSetChanged();
} else if (resultCode == RESULT_CANCELED && requestCode == REQUEST_ENABLE_BT) {
Log.e("text", "沒有開啟藍牙");
mSwitch.setChecked(false);
setViewStatus(false);
}

}

/**
* 打開藍牙
*/
public void openBluetooth() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 設置藍牙可見性,最多300秒
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 20);
startActivityForResult(intent, REQUEST_ENABLE_BT);

}

/**
* 關閉藍牙
*/
public void closeBluetooth() {
mBluetoothAdapter.disable();
}


/**
* 搜索藍牙設備
*/
public void searchDevices() {
mBluetoothDevicesDatas.clear();
adapter.notifyDataSetChanged();
//開始搜索藍牙設備
mBluetoothAdapter.startDiscovery();
}


/**
* 通過廣播搜索藍牙設備
*/
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
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) {
addBluetoothDevice(device);

//沒有匹配的設備
} else {
addBluetoothDevice(device);
}
adapter.notifyDataSetChanged();
//搜索完成
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setViewStatus(false);
}
}

/**
* 添加數據
* @param device 藍牙設置對象
*/
private void addBluetoothDevice(BluetoothDevice device) {
for (int i = 0; i < mBluetoothDevicesDatas.size(); i++) {
if (device.getAddress().equals(mBluetoothDevicesDatas.get(i).getAddress())) {
mBluetoothDevicesDatas.remove(i);
}
}
if (device.getBondState() == BluetoothDevice.BOND_BONDED && device.getBluetoothClass().getDeviceClass() == PRINT_TYPE) {
mBluetoothDevicesDatas.add(0, new PrintBean(device));
} else {
mBluetoothDevicesDatas.add(new PrintBean(device));
}
}
};


}

  

class PrintAdapter extends BaseAdapter {
private ArrayList<PrintBean> mBluetoothDevicesDatas;
private Context mContext;
//藍牙適配器
private BluetoothAdapter mBluetoothAdapter;
//藍牙socket對象
private BluetoothSocket mmSocket;
private UUID uuid;
//打印的輸出流
private static OutputStream outputStream = null;
//搜索彈窗提示
ProgressDialog progressDialog = null;
private final int exceptionCod = 100;
//打印的內容
private String mPrintContent;
//在打印異常時更新ui
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == exceptionCod) {
Toast.makeText(mContext, "打印發送失敗,請稍后再試", Toast.LENGTH_SHORT).show();
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
};

/**
* @param context 上下文
* @param mBluetoothDevicesDatas 設備列表
* @param printContent 打印的內容
*/
public PrintAdapter(Context context, ArrayList<PrintBean> mBluetoothDevicesDatas, String printContent) {
this.mBluetoothDevicesDatas = mBluetoothDevicesDatas;
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mPrintContent = printContent;
uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
}

public int getCount() {
return mBluetoothDevicesDatas.size();
}

@Override
public Object getItem(int position) {
return position;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.itme, null);
View icon = convertView.findViewById(R.id.icon);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView address = (TextView) convertView.findViewById(R.id.address);
TextView start = (TextView) convertView.findViewById(R.id.start);

final PrintBean dataBean = mBluetoothDevicesDatas.get(position);
icon.setBackgroundResource(dataBean.getTypeIcon());
name.setText(dataBean.name);
address.setText(dataBean.isConnect ? "已連接" : "未連接");
start.setText(dataBean.getDeviceType(start));

//點擊連接與打印
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
//如果已經連接並且是打印機
if (dataBean.isConnect && dataBean.getType() == PRINT_TYPE) {
if (mBluetoothAdapter.isEnabled()) {
new ConnectThread(mBluetoothAdapter.getRemoteDevice(dataBean.address)).start();
progressDialog = ProgressDialog.show(mContext, "提示", "正在打印...", true);
} else {
Toast.makeText(mContext, "藍牙沒有打開", Toast.LENGTH_SHORT).show();
}
//沒有連接
} else {
//是打印機
if (dataBean.getType() == PRINT_TYPE) {
setConnect(mBluetoothAdapter.getRemoteDevice(dataBean.address), position);
//不是打印機
} else {
Toast.makeText(mContext, "該設備不是打印機", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});

return convertView;
}

/**
* 匹配設備
*
* @param device 設備
*/
private void setConnect(BluetoothDevice device, int position) {
try {
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
createBondMethod.invoke(device);
mBluetoothDevicesDatas.get(position).setConnect(true);
notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 發送數據
*/
public void send(String sendData) {
try {
byte[] data = sendData.getBytes("gbk");
outputStream.write(data, 0, data.length);
outputStream.flush();
outputStream.close();
progressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
handler.sendEmptyMessage(exceptionCod); // 向Handler發送消息,更新UI

}
}

/**
* 連接為客戶端
*/
private class ConnectThread extends Thread {
public ConnectThread(BluetoothDevice device) {
try {
mmSocket = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
}

public void run() {
//取消的發現,因為它將減緩連接
mBluetoothAdapter.cancelDiscovery();
try {
//連接socket
mmSocket.connect();
//連接成功獲取輸出流
outputStream = mmSocket.getOutputStream();

send(mPrintContent);
} catch (Exception connectException) {
Log.e("test", "連接失敗");
connectException.printStackTrace();
//異常時發消息更新UI
Message msg = new Message();
msg.what = exceptionCod;
// 向Handler發送消息,更新UI
handler.sendMessage(msg);

try {
mmSocket.close();
} catch (Exception closeException) {
closeException.printStackTrace();
}
return;
}
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM