2014-02-18 5 views
4

블루투스 열 감지 프린터를 사용하고 있습니다. 프린터가 정상적으로 작동하지만 하나의 작업에서 프린터를 연결하고 다른 작업의 데이터를 인쇄하려고합니다. 인쇄 데이터에 연결해야 할 때마다 좋습니다. 프린터를 한 번 연결하고 연결을 유지하려는 응용 프로그램을 통해 연결하려고합니다. 이제 내 문제는 프린터에 연결 한 후입니다. 두 번째 작업으로 이동하면 프린터 연결이 끊깁니다.Android 블루투스 배경 스레드

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(); 
} 
+1

누가 이것을 upvoted? (아마도 전혀 관련이없는) 코드의 벽은 "연구 노력을 보여 주며 유용하고 분명한 것"으로 인정받지 못합니다. ''실에 대해서 들었지만 실천하는데 도움이 필요하다.''실의 기초에 관해 가르치는 곳이 아니다. –

+1

당신의 평판을 존중하는 선생. 나는 다른 선택의 여지가 없다. 전자 공학을 공부하고 IT 회사에서 일한다. – Comrade

+0

괜찮아. 문제 없어요. 지금 나는이 질문을 upvoted.please 새로운 guy.they stackoverflow 채팅 룸 – Venu

답변

0

그냥 블루투스 연결을 서비스로 옮기십시오.

+0

나는 이것을 안다. 그러나 나는 모른다. 어떻게 지냈나? 샘플이 있습니까? – Comrade