我在内部创建了MainActivity,我正在创建一个asynctask" AsyncTask"使用onPostExecute线程,我正在创建另一个名为" RecvdOptimusData"的线程。使用Android Studio。
public class optManControl extends AppCompatActivity {
....................
// The Handler obtains the data from the Socket
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case MSG_TYPE_BT_SENSOR: {
// Get the data from the msg.obj
String strReceived = null;
byte[] dataReceived = (byte[]) msg.obj;
if(dataReceived != null){
// construct a string from the valid bytes in the buffer
strReceived = new String(dataReceived, 0, msg.arg1);
if (strReceived != null) {
strReceived = trim(strReceived);
String[] values = split(strReceived, ',');
try {
msg("Setting Angle and Distance!");
imageDrawer.setAngle_Distance(values);
} catch (Exception e) {
msg("Angle-Distance Set Error");
}
}
else{
msg("Null str rcvd!!!");
}
}
else{
msg("Null data rcvd!!!");
}
}
break;
}
}
};
..........................
我们创建最终线程RecvdOptimusData的线程
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
@Override
protected void onPreExecute() {
alertView(R.string.title_dev_conn_progress);
//progress = ProgressDialog.show(optManControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
@Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try {
if (btSocket == null || !isBtConnected) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
//btSocket = mConnectedSco.createScoSocket();//Create SCO socket connection using either "mConnectedSco" OR "dispositivo" objects.
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
} catch (IOException e) {
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
@Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
Looper.prepare();
if (!ConnectSuccess) {
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
} else {
//Start new Thread to listen for data on BT port
msg("Connected. Let's start a new Thread!!!");
recvdOptimusData = new RecvdOptimusData();
new Thread(recvdOptimusData).start();
msg("Connected.!!!");
isBtConnected = true;
}
//progress.dismiss();
//dialog.create().dismiss();
OptionDialog.dismiss();
}
}
以下是我们想要创建的新主题
private class RecvdOptimusData implements Runnable{
public void run() {
byte[] buffer = new byte[1024]; // buffer to store the string
int bytes; // Number of bytes read
if (btSocket != null) {
msg("BTsocket ! NULL");
while (true) {
try {
msg("Reading Data from BT Socket sent by Optimus");
bytes = btSocket.getInputStream().read(buffer);
mHandler.obtainMessage(MSG_TYPE_BT_SENSOR, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
msg("BT Rcvd_Msg Read Error");
}
}
} else {
msg("BTsocket NULL");
}
}
}
}
堆栈跟踪
10-31 17:46:43.382 8727-8727/com.optimus.rccar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.optimus.rccar, PID: 8727
java.lang.RuntimeException: Only one Looper may be created per thread
at android.os.Looper.prepare(Looper.java:89)
at android.os.Looper.prepare(Looper.java:84)
at com.optimus.rccar.optManControl$ConnectBT.onPostExecute(optManControl.java:286)
at com.optimus.rccar.optManControl$ConnectBT.onPostExecute(optManControl.java:254)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6317)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)