Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/202.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android蓝牙后台线程_Android_Bluetooth_Android Bluetooth - Fatal编程技术网

Android蓝牙后台线程

Android蓝牙后台线程,android,bluetooth,android-bluetooth,Android,Bluetooth,Android Bluetooth,我正在使用蓝牙热敏打印机。打印机工作正常,但我想从一个活动连接打印机并从另一个活动打印数据。现在每次我必须连接到打印数据时。我想连接打印机一次,然后在整个应用程序中保持连接。现在我的问题是连接到打印机后,如果移动到第二个活动,打印机将断开连接 protected static final String TAG = "TAG"; private static final int REQUEST_CONNECT_DEVICE = 1; private static final int REQUES

我正在使用蓝牙热敏打印机。打印机工作正常,但我想从一个活动连接打印机并从另一个活动打印数据。现在每次我必须连接到打印数据时。我想连接打印机一次,然后在整个应用程序中保持连接。现在我的问题是连接到打印机后,如果移动到第二个活动,打印机将断开连接

 protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan, mPrint, mDisc;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
        .fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;

@Override
public void onCreate(Bundle mSavedInstanceState) {
    super.onCreate(mSavedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);
    mScan = (Button) findViewById(R.id.Scan);
    mScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View mView) {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (mBluetoothAdapter == null) {
                Toast.makeText(PrinterActivity.this, "Message1", 2000).show();
            } else {
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(
                            BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent,
                            REQUEST_ENABLE_BT);
                } else {
                    ListPairedDevices();
                    Intent connectIntent = new Intent(PrinterActivity.this,
                            DeviceListActivity.class);
                    startActivityForResult(connectIntent,
                            REQUEST_CONNECT_DEVICE);
                }
            }
        }
    });

    mPrint = (Button) findViewById(R.id.mPrint);
    mPrint.setOnClickListener(new View.OnClickListener() {
        public void onClick(View mView) {
            Thread t = new Thread() {
                public void run() {
                    try {
                        OutputStream os = mBluetoothSocket
                                .getOutputStream();
                        String BILL = "";

                        BILL = "\nInvoice No: ABCDEF28060000005" + "    "
                                + "04-08-2011\n";
                        BILL = BILL
                                + "-----------------------------------------";
                        BILL = BILL + "\n\n";
                        BILL = BILL + "Total Qty:" + "      " + "2.0\n";
                        BILL = BILL + "Total Value:" + "     "
                                + "17625.0\n";
                        BILL = BILL
                                + "-----------------------------------------\n";
                        os.write(BILL.getBytes());
                            //This is printer specific code you can comment ==== > Start

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

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

                       /* // Print BarCode
                        int gs1 = 29;
                        os.write(intToByteArray(gs1));
                        int k = 107;
                        os.write(intToByteArray(k));
                        int m = 73;
                        os.write(intToByteArray(m));

                        String barCodeVal = "ASDFC028060000005";// "HELLO12345678912345012";
                        System.out.println("Barcode Length : "
                                + barCodeVal.length());
                        int n1 = barCodeVal.length();
                        os.write(intToByteArray(n1));

                        for (int i = 0; i < barCodeVal.length(); i++) {
                            os.write((barCodeVal.charAt(i) + "").getBytes());
                        }
    *///printer specific code you can comment ==== > End
                    } catch (Exception e) {
                        Log.e("Main", "Exe ", e);
                    }
                }
            };
            t.start();
        }
    });

    mDisc = (Button) findViewById(R.id.dis);
    mDisc.setOnClickListener(new View.OnClickListener() {
        public void onClick(View mView) {
            if (mBluetoothAdapter != null)
                mBluetoothAdapter.disable();
        }
    });

}// onCreate

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    try {
        if (mBluetoothSocket != null)
            mBluetoothSocket.close();
    } catch (Exception e) {
        Log.e("Tag", "Exe ", e);
    }
}

@Override
public void onBackPressed() {
    try {
        if (mBluetoothSocket != null)
            mBluetoothSocket.close();
    } catch (Exception e) {
        Log.e("Tag", "Exe ", e);
    }
    setResult(RESULT_CANCELED);
    finish();
}

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);
            mBluetoothConnectProgressDialog = ProgressDialog.show(this,
                    "Connecting...", mBluetoothDevice.getName() + " : "
                            + mBluetoothDevice.getAddress(), true, false);
            Thread mBlutoothConnectThread = new Thread(this);
            mBlutoothConnectThread.start();
            // 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(PrinterActivity.this,
                    DeviceListActivity.class);
            startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
        } else {
            Toast.makeText(PrinterActivity.this, "Message", 2000).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());
        }
    }
}

public void run() {
    try {
        mBluetoothSocket = mBluetoothDevice
                .createRfcommSocketToServiceRecord(applicationUUID);
        mBluetoothAdapter.cancelDiscovery();
        mBluetoothSocket.connect();
        mHandler.sendEmptyMessage(0);
    } catch (IOException eConnectException) {
        Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
        closeSocket(mBluetoothSocket);
        return;
    }
}

private void closeSocket(BluetoothSocket nOpenSocket) {
    try {
        nOpenSocket.close();
        Log.d(TAG, "SocketClosed");
    } catch (IOException ex) {
        Log.d(TAG, "CouldNotCloseSocket");
    }
}

private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        mBluetoothConnectProgressDialog.dismiss();
        Toast.makeText(PrinterActivity.this, "DeviceConnected", 5000).show();
    }
};

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];
}

public byte[] sel(int val) {
    ByteBuffer buffer = ByteBuffer.allocate(2);
    buffer.putInt(val);
    buffer.flip();
    return buffer.array();
}
protected static final String TAG=“TAG”;
专用静态最终int请求\u连接\u设备=1;
私有静态最终整数请求_ENABLE_BT=2;
按钮mScan、mPrint、mDisc;
蓝牙适配器mBluetoothAdapter;
专用UUID应用程序UID=UUID
.fromString(“000011101-0000-1000-8000-00805F9B34FB”);
private ProgressDialog mBluetoothConnectProgressDialog;
私人蓝牙插座;
蓝牙设备;
@凌驾
创建时的公共void(Bundle mSavedInstanceState){
super.onCreate(mSavedInstanceState);
requestWindowFeature(窗口。功能\u无\u标题);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_全屏,
WindowManager.LayoutParams.FLAG(全屏);
setContentView(R.layout.activity_main);
mScan=(按钮)findViewById(R.id.Scan);
mScan.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图mView){
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter==null){
Toast.makeText(PrinterActivity.this,“Message1”,2000).show();
}否则{
如果(!mBluetoothAdapter.isEnabled()){
意图启用BTINTENT=新意图(
BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(启用BTIntent,
请求_启用_BT);
}否则{
ListPairedDevices();
意向连接意向=新意向(PrinterActivity.this,
DeviceListActivity.class);
startActivityForResult(康涅狄格州),
请求(连接设备);
}
}
}
});
mPrint=(按钮)findviewbyd(R.id.mPrint);
mPrint.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图mView){
线程t=新线程(){
公开募捐{
试一试{
OutputStream os=mBluetoothSocket
.getOutputStream();
字串比尔=”;
比尔=“\n语音编号:ABCDEF2806000005”+“”
+“04-08-2011\n”;
比尔=比尔
+ "-----------------------------------------";
账单=账单+“\n\n”;
账单=账单+“总数量:”+“+”2.0\n;
账单=账单+“总价值:”+“”
+“17625.0\n”;
比尔=比尔
+“--------------------------------------\n”;
write(BILL.getBytes());
//这是特定于打印机的代码,您可以注释==>开始
//设定高度
int gs=49;
写操作系统(intToByteArray(gs));
int h=104;
写入(intToByteArray(h));
int n=262;
写入(intToByteArray(n));
//设置宽度
int gs_宽度=49;
写入(intToByteArray(gs_宽度));
int w=104;
写操作系统(intToByteArray(w));
int n_宽度=2;
写入(intToByteArray(n_宽度));
/*//打印条形码
int gs1=29;
写操作系统(intToByteArray(gs1));
int k=107;
写操作系统(intToByteArray(k));
int m=73;
写操作系统(intToByteArray(m));
字符串barCodeVal=“asdfc028000005”/“hello1234567812345012”;
System.out.println(“条形码长度:
+barCodeVal.length());
int n1=条码值.length();
写操作系统(intToByteArray(n1));
对于(int i=0;i结束
}捕获(例外e){
Log.e(“Main”、“Exe”、e);
}
}
};
t、 start();
}
});
mDisc=(按钮)findViewById(R.id.dis);
mDisc.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图mView){
if(mBluetoothAdapter!=null)
mBluetoothAdapter.disable();
}
});
}//一次创建
@凌驾
受保护的空onDestroy(){
//TODO自动生成的方法存根
super.ondestory();
试一试{
如果(mBluetoothSocket!=null)
mBluetoothSocket.close();
}捕获(例外e){
Log.e(“Tag”、“Exe”、e);
}
}
@凌驾
public void onBackPressed(){
试一试{
如果(mBluetoothSocket!=null)
mBluetoothSocket.close();
}捕获(例外e){
Log.e(“Tag”、“Exe”、e);
}
setResult(结果被取消);
完成();
}
ActivityResult上的公共无效(int mRequestCode、int mResultCode、,
意图(mDataIntent){
super.onActivityResult(mRequestCode、mResultCode、mDataIntent);
开关(mRequ