我正在尝试通过以下步骤发送包含已扫描设备mac地址的post请求:1/扫描设备2/将设备mac地址发送到服务器3/返回带有“1”和“-1”的响应
-----如果1->设备正确
-----如果-1->设备不正确
通过列出设备是可以的,但发送post请求不起作用,捕获了服务器,没有发出请求
private void scanLeDevice(final boolean enable) {
final Button cancelButton = (Button) findViewById(R.id.btn_cancel);
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
uhf.stopScanBTDevices();
cancelButton.setText(R.string.scan);
}
}, SCAN_PERIOD);
mScanning = true;
uhf.startScanBTDevices(new ScanBTCallback() {
@Override
public void getDevices(final BluetoothDevice bluetoothDevice, final int rssi, byte[] bytes) {
runOnUiThread(new Runnable() {
@Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
String correct_device = "";
String device_mac = bluetoothDevice.getAddress();
String device_name = bluetoothDevice.getName();
// response correct_device = 1 == correct device, will available in list
// response correct_device = -1 == incorrect, does not need to appear in list
try {
url = new URL("http://10.10.10.212/api/is_correct_device/");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes("{ \"check_update\" : " + device_mac + " }");
os.flush();
os.close();
correct_device = conn.getResponseMessage();
} catch (Exception e) {
e.printStackTrace();
}
if (correct_device.equals("1")) {
MyDevice myDevice = new MyDevice(device_mac, device_name);
addDevice(myDevice, rssi);
}
conn.disconnect();
}
});
}
});
cancelButton.setText(R.string.cancel);
} else {
mScanning = false;
uhf.stopScanBTDevices();
cancelButton.setText(R.string.scan);
}
}
谢谢你救我!
1条答案
按热度按时间mrphzbgm1#
你在打电话吗
url.openConnection()
从runOnUiThread
.那是不可能的!
android中的所有网络通信代码都必须在后台线程中运行。
https://developer.android.com/training/basics/network-ops