我是蓝牙连接流程的新手。我正在为我的Android应用程序使用迷你热敏打印机设备。设备有自己的SDK。
当活动完成或被破坏时,我与设备的连接正在丢失。我如何修改以下代码以防止这种情况发生。
def net_weight
gross_weight - tare_weight
end
DeviceListActivity
PrintDemo Activity
package com.zj.printdemo;
import com.zj.printdemo.R;
import android.content.Intent;
import com.zj.btsdk.BluetoothService;
import com.zj.btsdk.PrintPic;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
public class PrintDemo extends Activity {
Button btnSearch;
Button btnSendDraw;
Button btnSend;
Button btnClose;
EditText edtContext;
EditText edtPrint;
private static final int REQUEST_ENABLE_BT = 2;
BluetoothService mService = null;
BluetoothDevice con_dev = null;
private static final int REQUEST_CONNECT_DEVICE = 1; //��ȡ�豸��Ϣ
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mService = new BluetoothService(this, mHandler);
//�����������˳�����
if( mService.isAvailable() == false ){
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void onStart() {
super.onStart();
//�����������
if( mService.isBTopen() == false)
{
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_test);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btnSend);
btnSend.setOnClickListener(new ClickEvent());
btnClose = (Button) this.findViewById(R.id.btnClose);
btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
btnClose.setEnabled(false);
btnSend.setEnabled(false);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("������Ϣ",ex.getMessage());
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this,DeviceListActivity.class); //��������һ����Ļ
startActivityForResult(serverIntent,REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
String msg = edtContext.getText().toString();
if( msg.length() > 0 ){
mService.sendMessage(msg+"\n", "GBK");
}
} else if (v == btnClose) {
mService.stop();
} else if (v == btnSendDraw) {
String msg = "";
String lang = getString(R.string.strLang);
//printImage();
byte[] cmd = new byte[3];
cmd[0] = 0x1b;
cmd[1] = 0x21;
if((lang.compareTo("en")) == 0){
cmd[2] |= 0x10;
mService.write(cmd); //��������ģʽ
mService.sendMessage("Congratulations!\n", "GBK");
cmd[2] &= 0xEF;
mService.write(cmd); //ȡ�����ߡ�����ģʽ
msg = " You have sucessfully created communications between your device and our bluetooth printer.\n\n"
+" the company is a high-tech enterprise which specializes" +
" in R&D,manufacturing,marketing of thermal printers and barcode scanners.\n\n";
mService.sendMessage(msg,"GBK");
}else if((lang.compareTo("ch")) == 0){
cmd[2] |= 0x10;
mService.write(cmd); //��������ģʽ
mService.sendMessage("��ϲ����\n", "GBK");
cmd[2] &= 0xEF;
mService.write(cmd); //ȡ�����ߡ�����ģʽ
msg = " ���Ѿ��ɹ��������������ǵ�������ӡ����\n\n"
+ " ����˾��һ��רҵ�����з�����������������Ʊ�ݴ�ӡ��������ɨ���豸��һ��ĸ߿Ƽ���ҵ.\n\n";
mService.sendMessage(msg,"GBK");
}
}
}
}
/**
* ����һ��Handlerʵ�������ڽ���BluetoothService��ػ�������Ϣ
*/
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED: //������
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING: //��������
Log.d("��������","��������.....");
break;
case BluetoothService.STATE_LISTEN: //�������ӵĵ���
case BluetoothService.STATE_NONE:
Log.d("��������","�ȴ�����.....");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST: //�����ѶϿ�����
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(false);
btnSend.setEnabled(false);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT: //�������豸
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT: //���������
if (resultCode == Activity.RESULT_OK) { //�����Ѿ���
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else { //�û������������
finish();
}
break;
case REQUEST_CONNECT_DEVICE: //��������ijһ�����豸
if (resultCode == Activity.RESULT_OK) { //�ѵ�������б��е�ij���豸��
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); //��ȡ�б������豸��mac��ַ
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
}
}
//��ӡͼ��
@SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData = null;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, "/mnt/sdcard/icon.jpg");
sendData = pg.printDraw();
mService.write(sendData); //��ӡbyte������
}
}
我尝试删除 public class DeviceListActivity extends Activity {
// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
BluetoothService mService = null;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list); //��ʾ�б����
// Set result CANCELED incase the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
mService = new BluetoothService(this, null);
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mService.getPairedDev();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mService != null) {
mService.cancelDiscovery();
}
mService = null;
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mService.isDiscovering()) {
mService.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mService.startDiscovery();
}
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() { //����б�������豸
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mService.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
Log.d("���ӵ�ַ", address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
,但似乎无效。