我想要做什么:
使用 Asynctask 启动应用程序时,我获得了与配对设备的蓝牙连接。-->new ConnectTask().execute("AMVCarsharingKit");
这非常适合第一次连接。
然后我有一个带有 Timer 的 TimerTask,如果发送了来自其他设备的消息,它会“看起来”。如果发送了正确的消息,则将执行相应的 if。当第一个连接运行时,这也可以正常工作。
现在到了重要的一点。我有一个 BroadcastReceiver 用于观看设备是否正在充电。我的清单中有这个:
<receiver android:name=".ChargingOnReceiver" android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
</intent-filter>
</receiver>
<receiver android:name=".NotChargingOnReceiver" android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
这也很好用。当它不再充电时,我禁用蓝牙并关闭插座(看下面的代码)。工作正常。
当它再次充电时,我再次启用蓝牙并启动将完成主要部分的 Activity。在此活动中,我必须再次重新连接到另一台设备(请参阅下面的 oncreat)。这种重新连接也有效(看起来如此)。
我也可以毫无问题地收到来自其他设备的消息。但是,当与其他蓝牙设备的第二次连接运行时,具有许多 if-terms 的 Timertask 会永久查找收到的消息,这会产生问题。我正确接收消息并执行了正确的 if 子句,但大多数时候它不执行 if 子句中的命令。例如,它不会进入 viewflipper 的右视图。除了“调用 if 子句”之外,它一直都能完美运行。
我真的不知道为什么会发生这种情况,或者说这没有发生。有谁知道什么可能是错误的或影响代码?
设备未充电时的广播接收器(截取代码):
Context applicationContext = CheckVehicleActivity
.getContextOfApplication();
//Disable bluetooth
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
MyApplication app = (MyApplication) applicationContext;
app.setIsCharging(false);
mmSocket = app.getmSocket();
try {
mmSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
设备再次充电时的广播接收器(截断代码):
Context applicationContext = CheckVehicleActivity
.getContextOfApplication();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.enable();
MyApplication app = (MyApplication) applicationContext;
app.setIsCharging(true);
Intent i = new Intent(context, CheckVehicleActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
onCreate(截断代码):
// executed when it's charging again
Boolean isCharging = app.getIsCharging();
if(isCharging == true){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
MyApplication app = (MyApplication) getApplicationContext();
new ConnectTask().execute("AMVCarsharingKit");
app.setIsCharging(false);
}
}, 3000);
}else{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.enable();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
MyApplication app = (MyApplication) getApplicationContext();
new ConnectTask().execute("AMVCarsharingKit");
app.setIsCharging(false);
}
}, 3000);
}
// Cyclic reading of incoming messages
TimerTask task = new TimerTask() {
@Override
public void run() {
pHandler.post(new Runnable() {
@Override
public void run() {
try {
new ReadTask().execute();
MyApplication app = (MyApplication) getApplicationContext();
app.setReceivedMsg(receivedMsg);
if (receivedMsg.contains(HANDY_ON)) {
int id = viewFlipper.getDisplayedChild();
if (id == 0) {
showSoftKeyboard();
}
pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
BrightnessUp();
receivedMsg = null;
}
if (receivedMsg.contains(HANDY_OFF)) {
// Go to login screen
viewFlipper.setDisplayedChild(0);
BrightnessDown();
if (wakeLock.isHeld())
wakeLock.release();
receivedMsg = null;
}
if (receivedMsg.contains(KEY_OUT)) {
viewFlipper.setDisplayedChild(4);
driveModus = true;
counterDrive = true;
startCounter();
receivedMsg = null;
}
if (receivedMsg.contains(CALL_ON)) {
vfID = viewFlipper.getDisplayedChild();
app.setVfId(vfID);
// Register the intent for phone call
Intent callIntent = new Intent(
Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:12345678"));
app.setPhone(1);
startActivityForResult(callIntent, 1);
receivedMsg = null;
}
if (receivedMsg.contains(FUELCARD_OUT)) {
int vfIDf = viewFlipper.getDisplayedChild();
app.setVfId(vfIDf);
if(vfIDf == 0){
hideSoftKeyboard();
}
if (driveModus == true) {
// Parse the tank PIN
int start = receivedMsg.indexOf(".") + 1;
int end = receivedMsg.length() - start;
tankPIN = String.copyValueOf(
receivedMsg.toCharArray(), start,
end);
txtTankID.setText(tankPIN);
viewFlipper.setDisplayedChild(5);
countDownTimer.start();
handler();
} else if (endModus == true) {
fuelNotAllowed
.setText("You already finished your booking. Please put the fuelcard back to the box.");
viewFlipper.setDisplayedChild(9);
} else {
viewFlipper.setDisplayedChild(9);
}
receivedMsg = null;
}
if (receivedMsg.contains(FUELCARD_IN)) {
int id = app.getVfId();
viewFlipper.setDisplayedChild(id);
if(id==0){
showSoftKeyboard();
}
BrightnessUp();
receivedMsg = null;
}
if (receivedMsg.contains(KEY_IN)) {
viewFlipper.setDisplayedChild(7);
System.out.println("KeyIn-Check: " + receivedMsg);
receivedMsg = null;
}
} catch (Exception e) {
System.out.println("Async-Check: " + receivedMsg);
System.out.println(e);
}
}
});
}
};
timer.schedule(task, 0, 1000);
用于蓝牙连接的 AsyncTask:
// Get bluetooth connection to the device
private class ConnectTask extends
AsyncTask<String, String, BluetoothSocket> {
BluetoothDevice mmDevice;
Set<BluetoothDevice> mBluetoothAdapter;
@Override
protected BluetoothSocket doInBackground(String... params) {
try {
MyApplication app = (MyApplication) getApplicationContext();
bAdapter = BluetoothAdapter
.getDefaultAdapter();
// Get the all devices which are bonded
mBluetoothAdapter = bAdapter.getBondedDevices();
for (BluetoothDevice bc : mBluetoothAdapter) {
if (bc.getName().indexOf("AMVCarsharingKit") != -1) {
UUID uuid = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard
// SerialPortService
// ID
mmDevice = bc;
mmSocket = mmDevice
.createInsecureRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
BufferedWriter Writer = new BufferedWriter(
new OutputStreamWriter(
mmSocket.getOutputStream()));
Writer.write(BLUETOOTH_CONNECTED);
Writer.flush();
app.setmSocket(mmSocket);
break;
}
}
return mmSocket;
} catch(IOException e){
bAdapter.cancelDiscovery();
}
catch (Exception ex) {
System.out.println(ex);
}
return null;
}
}
AsyncTask 用于从连接的设备中读取:
// Read messages which are send from the connected device
private static class ReadTask extends
AsyncTask<String, String, BluetoothSocket> {
@Override
protected BluetoothSocket doInBackground(String... params) {
try {
System.out.println("Test: Before Reader");
BufferedReader Reader = new BufferedReader(
new InputStreamReader(mmSocket.getInputStream()));
receivedMsg = Reader.readLine();
System.out.println("Reader: " + receivedMsg);
} catch (Exception ex) {
System.out.println(ex);
}
return null;
}
protected void onPostExecute(BluetoothSocket result) {
}
}