Android 活动重新加载时蓝牙连接丢失
我正在尝试连接蓝牙打印机设备,每次重新加载活动时,连接都会丢失。原因可能是什么?单击“下一步”按钮时,活动正在重新加载 代码如下:Android 活动重新加载时蓝牙连接丢失,android,sockets,bluetooth,Android,Sockets,Bluetooth,我正在尝试连接蓝牙打印机设备,每次重新加载活动时,连接都会丢失。原因可能是什么?单击“下一步”按钮时,活动正在重新加载 代码如下: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_sales_return); mActivity = Activity_Sales
@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);
}}}}}
@覆盖
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout\u sales\u return);
mActivity=活动\销售\退货。此;
if(internet.HaveNetworkConnection()){
试一试{
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
试一试{
statusBT=false;
enableBT();
openBT();
}捕获(IOEX异常){
例如printStackTrace();
}
}
}
void findBT(){
试一试{
设置pairedDevices=mBluetoothAdapter
.getBondedDevices();
如果(pairedDevices.size()>0){
用于(蓝牙设备:pairedDevices){
if(device.getName().equalsIgnoreCase(bt_Name.trim()))
{
mmDevice=设备;
打破
}
}
}
showToast(“找到蓝牙设备”);
}捕获(NullPointerException e){
e、 printStackTrace();
}捕获(例外e){
e、 printStackTrace();
}
}
void enableBT(){
试一试{
if(mBluetoothAdapter==null){
}
if(mBluetoothAdapter.isEnabled()){
findBT();
}
}捕获(例外e){
e、 printStackTrace();
}
}
//尝试打开与蓝牙打印机设备的连接
void openBT()引发IOException{
试一试{
//标准SerialPortService ID
UUID UUID=UUID.fromString(“00001101-0000-1000-8000-
00805F9B34FB”);
System.out.println(“==mmdevice:+mmdevice”);
mmSocket=mmDevice.createRfcommSocketToServiceRecord(UUID
.fromString(“000011101-0000-1000-8000-00805F9B34FB”);
mmSocket.connect();
mmOutputStream=mmSocket.getOutputStream();
mmInputStream=mmSocket.getInputStream();
beginListenForData();
showToast(“蓝牙已打开”);
}捕获(NullPointerException e){
showToast(“无法连接设备,请重试”);
e、 printStackTrace();
}捕获(例外e){
showToast(“无法连接设备,请重试”);
e、 printStackTrace();
}
}
//打开与蓝牙打印机设备的连接后,
//我们必须倾听并检查是否发送了数据进行打印。
void beginListenForData(){
试一试{
最终处理程序=新处理程序();
//这是换行符的ASCII码
最后一个字节分隔符=10;
stopWorker=false;
readBufferPosition=0;
readBuffer=新字节[1024];
workerThread=新线程(new Runnable()){
公开募捐{
而(!Thread.currentThread().isInterrupted()
&&!停车工人){
试一试{
int bytesavable=mmInputStream.available();
如果(字节可用>0){
byte[]packetBytes=新字节[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i