i'm trying to send post request contain mac address of scanned devices by the following steps: 1/ scan devices 2/ send device mac addr to server 3/ return response with "1" and "-1"
-----if 1 -> device is correct
-----if -1 -> device is incorrect
By listing device is ok, but sending post request does not working, captured server, no request was made
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);
}
}
Thanks for save me!
You are calling url.openConnection()
from runOnUiThread
.
That is not possible!
All network communication code in Android must run in a background thread.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.