我正在尝试连接蓝牙打印机设备,每次重新加载活动时连接都会丢失。可能是什么原因?单击“下一步”按钮时,活动正在重新加载。
以下是代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_sales_return);
mActivity = Activity_Sales_Return.this;
if(internet.HaveNetworkConnection()){
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
try {
statusBT = false;
enableBT();
openBT();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
void findBT() {
try {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equalsIgnoreCase(bt_Name.trim()))
{
mmDevice = device;
break;
}
}
}
showToast("Bluetooth Device Found");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
void enableBT(){
try{
if (mBluetoothAdapter == null) {
}
if (mBluetoothAdapter.isEnabled()) {
findBT();
}
}catch(Exception e){
e.printStackTrace();
}
}
// Tries to open a connection to the bluetooth printer device
void openBT() throws IOException {
try {
// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-
00805F9B34FB");
System.out.println("====mmdevice: "+mmDevice);
mmSocket = mmDevice.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
showToast("Bluetooth Opened");
} catch (NullPointerException e) {
showToast("Unable to connect device, Please try again.");
e.printStackTrace();
} catch (Exception e) {
showToast("Unable to connect device, Please try again.");
e.printStackTrace();
}
}
// After opening a connection to bluetooth printer device,
// we have to listen and check if a data were sent to be printed.
void beginListenForData() {
try {
final Handler handler = new Handler();
// This is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()
&& !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new
byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
showToast(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send data to be printed by the bluetooth printer
*/
void sendData() throws IOException {
try {
// the text typed by the user
String msg = "hiii";
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
showToast("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Close the connection to bluetooth printer.
void closeBT() throws IOException {
System.out.println("====mmOutputStream:"+mmOutputStream);
if(mmOutputStream!=null && mmInputStream!=null && mmSocket!=null){
try {
System.out.println("===-----=mmOutputStream:"+mmOutputStream);
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
showToast("Bluetooth Closed");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (internet.HaveNetworkConnection() ) {
try {
if(statusBT ){
if (mService != null)
mService.stop();
}else{
closeBT();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String uploadFile(String sourceFileUri) {
System.out.println("lol");
CheckInternetConnection internet = new CheckInternetConnection(
Activity_Sales_Return.this);
if (!internet.HaveNetworkConnection()) {
return "No Internet";
}
String serverResponse = "";
final String fileName = sourceFileUri;
InputStream is = null;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024, serverResponseCode;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile",
"Source File not exist :"
+ Environment.getExternalStorageDirectory() + "/"
+ Utility.SALE_FILE_NAME);
return "";
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(Utility.BASE_URL
+ "?q=webservice/send_order&token=" + api_token);
System.out.println("======url: "+url);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("xml", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"xml\"; filename='"
+ fileName + "'" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
System.out.println("=======ff:" + toPrettyString(fileName, 4));
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
System.out.println("----------" + serverResponseMessage);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
showToast("Order Completed."); // Activity Reloading
// here
try {
sendData();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
is = new DataInputStream(conn.getInputStream());
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
serverResponse = sb.toString();
fileInputStream.close();
dos.flush();
dos.close();
is.close();
dialog.dismiss();
return serverResponse;
} catch (Exception e) {
e.printStackTrace();
}
dialog.dismiss();
return "";
}
}
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
new Thread(new Runnable() {
public void run() {
final String serverResponse = uploadFile(Environment
.getExternalStorageDirectory()+ "/"+ Utility.SALE_FILE_NAME);
}}}}}