我正在尝试通过蓝牙接收手机上的数据,而我正在使用Android Studio尝试此操作。问题是,当我运行一个侦听传入数据的进程时,我认为程序在进程中停止并等待,而不允许程序的其余部分运行。我相信这是因为我编写Toast以在调用方法后立即显示“Data listening for”,但即使发送数据也没有任何反应。如果问题看起来很基本,我提前道歉,这是我的第一个应用程序。我想我读到某个地方,beginListenForData()将需要在另一个步骤上运行来阻止这个确切的问题,是吗?我该怎么做呢?
这是mainActivity代码:
package com.example.root.test2;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.*;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private final int REQUEST_ENABLE_BT = 1;
private UUID MY_UUID = UUID.fromString("d095b825-4e33-42e8-a7d0-b22fee285386");
ListView pairedDevicesW;
String info;
String info_MAC;
String info_Name;
private BluetoothSocket BTS;
private BluetoothDevice BTD;
private BluetoothAdapter BTA = BluetoothAdapter.getDefaultAdapter();
Button B_Disconnect;
Button B_Send_Data;
boolean is_Receiving = true;
InputStream inStream;
volatile boolean stopWorker;
int readBufferPosition;
int counter;
byte[] readBuffer;
Thread workerThread;
String finalData;
void beginListenForData() {
final Handler handler = new Handler();
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 = inStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
inStream.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() {
@Override
public void run() {
finalData = data;
}
});
}
else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException e) {
Log.d("TAG", e.toString());
stopWorker = true;
} catch (NullPointerException z) {
Log.d("TAG", z.toString());
stopWorker = true;
}
}
}
});
workerThread.start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> pairedDevicesA= new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, pairedDevicesA);
pairedDevicesW = (ListView)findViewById(R.id.PDL);
B_Disconnect = (Button)findViewById(R.id.B_Disconnect);
B_Send_Data = (Button)findViewById(R.id.B_Send_Data);
if (BTA == null) {
Toast.makeText(getApplication().getBaseContext(), "Bluetooth not supported", Toast.LENGTH_SHORT).show();
}
if (!BTA.isEnabled()) {
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
}
final Set<BluetoothDevice> pairedDevices = BTA.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice BTDevice : pairedDevices) {
pairedDevicesA.add(BTDevice.getAddress() + "\n" + BTDevice.getName());
}
}
pairedDevicesW.setAdapter(adapter);
pairedDevicesW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
info = ((TextView)view).getText().toString();
info_MAC = info.substring(0, 17);
info_Name = info.substring(18);
Toast.makeText(getBaseContext(), "Onclicklistenerstarted", Toast.LENGTH_SHORT).show();
for (BluetoothDevice BTDevice : pairedDevices) {
if (BTDevice.getAddress().equals(info_MAC)) {
BTD = BTDevice;
}
}
Toast.makeText(getBaseContext(), "BTD set", Toast.LENGTH_SHORT).show();
BluetoothSocket temp = null;
try {
temp = BTD.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.d("CONNECTTHREAD", "Could not create socket; " + e.toString());
} catch (NullPointerException z) {
Log.d("CONNECTTREAD", z.toString());
}
BTS = temp;
Toast.makeText(getBaseContext(), "Socket set", Toast.LENGTH_SHORT).show();
if (BTS != null) {
Toast.makeText(getBaseContext(), "Socket not null", Toast.LENGTH_SHORT).show();
try {
BTS.connect();
Toast.makeText(getBaseContext(), "Connection Finally Fucking Made", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.d("CONNECTTHREAD", "Could not connect; " + e.toString());
try {
BTS.close();
Toast.makeText(getBaseContext(), "Connection prematurely closed", Toast.LENGTH_SHORT).show();
} catch (IOException close) {
Log.d("CONNECTTHREAD", "Could not close connection; " + close.toString());
}
}
Toast.makeText(getBaseContext(), "Loop complete", Toast.LENGTH_SHORT).show();
}
}
});
InputStream tmpIn = null;
try {
tmpIn = BTS.getInputStream();
} catch (IOException e) {
Log.d("INPUTSTREAM", e.toString());
} catch (NullPointerException z) {
Log.d("NPE", z.toString());
}
inStream = tmpIn;
Toast.makeText(getBaseContext(), "Input Stream Made", Toast.LENGTH_SHORT).show();
while (is_Receiving) {
beginListenForData();
Toast.makeText(getBaseContext(), "Data listened for", Toast.LENGTH_SHORT).show();
if (finalData != "") {
Toast.makeText(getBaseContext(), "Data not null", Toast.LENGTH_SHORT).show();
try {
Toast.makeText(getBaseContext(), finalData.toString(), Toast.LENGTH_SHORT).show();
} catch (NullPointerException e) {
}
} else {
Toast.makeText(getBaseContext(), "No Data", Toast.LENGTH_SHORT).show();
}
B_Disconnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
BTS.close();
Toast.makeText(getBaseContext(), "Connection Closed", Toast.LENGTH_SHORT).show();
} catch (IOException e) {}
is_Receiving = false;
}
});
is_Receiving = false;
}
}
}
答案 0 :(得分:0)
我认为你应该考虑使用AsyncTask来执行后台操作。 链接:http://developer.android.com/reference/android/os/AsyncTask.html