Android BLE peripheral device data receiving - java

This might sound really basic but I'm a beginner at Android BLE Development.
So far I am able to Create my Nexus 9 device as a peripheral device and Moto G as Central. Plus i'm connecting the devices successfully. But i cant figure out that when i send a characteristic from central device where will it be received from peripheral? The Advertise call back only return if advertisement is started successfully of not(Which in my case is successful)
Here is my peripheral Code
btleGattCallback = new BluetoothGattCallback() {
#Override
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
#Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
// this will get called when a device connects or disconnects
}
#Override
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w("doscover", "onServicesDiscovered received: " + status);
}
}
};
BeaconParser bp = new BeaconParser().setBeaconLayout("m:2-3=0,i:4-19,p:20-20");
mBeaconTransmitter = new BeaconTransmitter(this, bp );
// Transmit a beacon with Identifiers 2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6 1 2
Long li = new Long(-0l);
ArrayList<Long> l = new ArrayList<Long>();
l.add(li);
Beacon beacon = new Beacon.Builder()
.setId1("2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6")
.setId2("1")
.setId3("2")
.setManufacturer(0x00ff) // Choose a number of 0x00ff or less as some devices cannot detect beacons with a manufacturer code > 0x00ff
.setTxPower(-59)
.setDataFields(l)
.build();
mBeaconTransmitter.startAdvertising(beacon);
And the Central Code ofcorse
btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE) ;
madapter = btManager.getAdapter();
if (madapter != null && !madapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,1);
}
mHandler = new Handler();
btleGattCallback = new BluetoothGattCallback() {
#Override
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
#Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
Log.w("doscover", "Connected " + status);
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.w("discover", "onServicesDiscovered received: " + status);
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w("doscover", "onServicesDiscovered received: " + status);
}
}
};
devicefound = new ArrayList<BluetoothDevice>();
devices = new ArrayAdapter<String>( this , R.layout.device_name);
ListView pairedListView = (ListView) findViewById(R.id.textView3);
pairedListView.setAdapter(devices);
mleScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
devicefound.add(device);
//UUID = device.getAddress().toString();
//Log.e("Search", "" + device.getName().toString() );
//Toast`.makeText(context,device.getName().toString(), 1 ).show();
Log.e("Search", "" + device.toString());
Log.e("Search", "" + String.valueOf(rssi) );
devices.add("Nex" + device.getName() );
//mBluetoothGatt = device.connectGatt(getActivity(), true, btleGattCallback);
}
};
pairedListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View arg1,
int position, long id) {
dv = devicefound.get(position);
mBluetoothGatt = dv.connectGatt(getApplicationContext() , true, btleGattCallback);
mBluetoothGatt.connect();
dv.createBond();
//BluetoothDevice dd = madapter.getRemoteDevice(devicefound.get(position).getAddress());
if(i == false)
{
Toast.makeText(getApplicationContext(), "Service found. Connected to " + dv.getName() , 1).show();
}
else
{
Toast.makeText(getApplicationContext(), "Already Connected " + dv.getName() , 1).show();
}
i = mBluetoothGatt.connect();
mBluetoothGatt.beginReliableWrite();
boolean b = mBluetoothGatt.discoverServices();
Log.e("Discovery Started", "" + b );
Log.e("get ItemATPosition", "" + adapter.getItemAtPosition(position));
//BluetoothGattService Service = mBluetoothGatt.getService( );
// = Service.getCharacteristic(k);
BluetoothGattCharacteristic characteristic= new BluetoothGattCharacteristic(k,2,1); //Service
characteristic.setValue( "This is a Charects ");
byte[] value = {(byte)91,(byte)92,(byte)93};
characteristic.setValue(value);
boolean st = mBluetoothGatt.writeCharacteristic(characteristic);
//Toast.makeText(getActivity(), t1.getText() + " " + st, 1).show();
boolean b1 = mBluetoothGatt.executeReliableWrite();
//Toast.makeText(getActivity(), t1.getText() + " " + b1, 1).show();
Intent in = new Intent("ACTION_BOND_STATE_CHANGED.");
sendBroadcast(in);
}
});
scanLeDevice(true);
I'm using the writeCharacteristic command of the connected Gatt from central but dont know how to receive from Peripheral end
Any sort of Help will be appreciated.

peripheral mode may support good on IOS, I suggest you use light blue for test purpose, from here:https://itunes.apple.com/us/app/lightblue-bluetooth-low-energy/id557428110?mt=8
and as I know Lollipop 5 installed on nexus 6 and nexus 9 can support peripheral mode, nexus 5 do not support it.
Moto G support peripheral mode?

Related

How to check if remote user or user internet disconnects or not in video call

I am making a video call app. I want to make a reconnection scenario just like whatsapp i.e. if the user or remote user internet disconnects after waiting for 10-15 seconds call should end for both. here is my code:
private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (AppSharedPreferences.getUser(context).getUserTypeId() == 2) {
updateDoctorStatus("3");
}
Log.e("Agora", "Join channel success, uid: " + (uid & 0xFFFFFFFFL));
}
});
}
#Override
public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("Agora", "First remote video decoded, uid: " + (uid & 0xFFFFFFFFL));
reconnectingView.setVisibility(View.GONE);
timerRunning = true;
appointmentStarted = true;
if (reconnecting) {
timeLeftInMillis = AppSharedPreferences.getCallTimer(VideoChatViewActivity.this);
countDownTimer.cancel();
}
callingView.setVisibility(View.GONE);
handler.removeCallbacks(runnableCode);
callHandler.removeCallbacks(runnableforCalling);
startMeeting();
updateAppointmentStatus();
setupRemoteVideo(uid);
}
});
}
#Override
public void onUserOffline(final int uid, final int reason) {
Log.e("Agora", "User offline, reason: " + reason);
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
boolean connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("Agora", "User offline, uid: " + (uid & 0xFFFFFFFFL));
if (reason == 0) {
onRemoteUserLeft();
endCall();
} else {
timerRunning = false;
reconnecting = true;
reconnectingView.setVisibility(View.VISIBLE);
reconnectingText.setText("Reconnecting....");
Toast.makeText(VideoChatViewActivity.this, "Doctor internet disconnected", Toast.LENGTH_LONG).show();
reconnectingHandler.postDelayed(() -> {
if (reconnecting) {
onRemoteUserLeft();
endCall();
}
}, 10000);
}
}
});
}
#Override
public void onUserMuteVideo(final int uid, final boolean muted) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("Agora", "User Muted, uid: " + (uid & 0xFFFFFFFFL));
Log.e("Agora", "User Muted,: " + muted);
if (muted)
remote_off.setVisibility(View.VISIBLE);
else
remote_off.setVisibility(View.GONE);
}
});
}
#Override
public void onRejoinChannelSuccess(String channel, int uid, int elapsed) {
super.onRejoinChannelSuccess(channel, uid, elapsed);
reconnecting = false;
Toast.makeText(VideoChatViewActivity.this, "Reconnected", Toast.LENGTH_LONG).show();
}
#Override
public void onNetworkQuality(int uid, final int txQuality, final int rxQuality) {
runOnUiThread(() -> {
// Log.e("Quality", rxQuality + "");
if (rxQuality == Quality.VBAD) {
signals.setImageDrawable(getResources().getDrawable(R.drawable.signal1));
}
if (rxQuality == Quality.BAD) {
signals.setImageDrawable(getResources().getDrawable(R.drawable.signal2));
}
if (rxQuality == Quality.POOR) {
signals.setImageDrawable(getResources().getDrawable(R.drawable.signal3));
}
if (rxQuality == Quality.GOOD) {
signals.setImageDrawable(getResources().getDrawable(R.drawable.signal4));
}
if (rxQuality == Quality.EXCELLENT) {
signals.setImageDrawable(getResources().getDrawable(R.drawable.signal5));
}
});
}
#Override
public void onConnectionStateChanged(int state, int reason) {
Log.d(TAG, "Connection state changes to "
+ state + " reason: " + reason);
}
};
Any help will be appreciated. In the code above there is a problem, I have used a handler in onUserOffline method which will end call after 10 seconds of user offline, but if the user reconnects within 10 seconds the handler still works and the call ends after 10 seconds.
Instead of using handler, I'd prefer you to use CountDownTimer. In this, you can also stop it in the middle. You can refer the code below:
//In your class
CountDownTimer mCountDownTimer;
//when the network goes
mCountDownTimer = new CountDownTimer((10 * 1000), (1 * 1000)){ // multiple the number of seconds by thousand to get the appropriate results. Here 10 * 1000 = 10000(10 seconds) and 1 * 1000 = 1000(1 second)
#Override
public void onTick(long millisInFuture){}
#Override
public void onFinish(){
//10 seconds have finished. Drop the call.
}
}.start();
//If the internet comes back
if(mCountDownTimer != null)
mCountDownTimer.cancel();

Not Connecting Gatt Server

I trying to connect two android device over the Gatt Protocol.
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.ParcelUuid;
import android.util.Log;
import java.util.HashSet;
import java.util.Set;
public class GattServer {
private final String TAG = GattServer.class.getSimpleName();
private Context applicationContext;
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private LocationManager locationManager;
BluetoothLeAdvertiser bluetoothLeAdvertiser;
private static GattServer gattServer;
private BluetoothGattServer bluetoothGattServer;
private Set<BluetoothDevice> connectedDevices = new HashSet<>();
public GattServer(Context applicationContext) {
this.applicationContext = applicationContext;
bluetoothManager = (BluetoothManager) applicationContext.getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
locationManager = (LocationManager) applicationContext.getSystemService(Context.LOCATION_SERVICE);
registerBluetoothStateReceiver();
}
public static GattServer getInstance(Context context) {
if (gattServer == null) {
gattServer = new GattServer(context.getApplicationContext());
}
return gattServer;
}
private BroadcastReceiver bluetoothStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
switch (state) {
case BluetoothAdapter.STATE_ON:
println("Bluetooth adapter state is changed to ON");
break;
case BluetoothAdapter.STATE_OFF:
println("Bluetooth adapter state is changed to OF");
break;
default:
// Do nothing
}
}
};
private void println(String message) {
Log.e(TAG, message);
}
private void registerBluetoothStateReceiver() {
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
try {
applicationContext.registerReceiver(bluetoothStateReceiver, filter);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unregisterBluetoothStateReceiver() {
try {
applicationContext.unregisterReceiver(bluetoothStateReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}
public void destroy() {
stop();
unregisterBluetoothStateReceiver();
gattServer = null;
}
private AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
#Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
println("Advertise Started");
listener.onAdvertiseStarted();
}
#Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
println("Advertise Failed : " + errorCode);
listener.onAdvertiseFail(errorCode);
}
};
private void startAdvertising() {
bluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
if (bluetoothLeAdvertiser == null || !bluetoothAdapter.isMultipleAdvertisementSupported()) {
Log.e(TAG, "Failed to create advertiser");
listener.onAdvertiseFail(-1);
return;
}
AdvertiseSettings settings = new AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
.setConnectable(true)
.setTimeout(0)
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
.build();
AdvertiseData data = new AdvertiseData.Builder()
.setIncludeDeviceName(true)
.setIncludeTxPowerLevel(false)
.addServiceUuid(new ParcelUuid(GattServerConfiguration.SERVICE_UUID))
.build();
bluetoothLeAdvertiser.startAdvertising(settings, data, advertiseCallback);
}
private BluetoothGattServerCallback gattCallback = new BluetoothGattServerCallback() {
#Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
println("Device Connected : " + device.getAddress());
connectedDevices.add(device);
listener.onDeviceConnected(device);
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
println("Device Disconnected : " + device.getAddress());
connectedDevices.remove(device);
listener.onDeviceDisconnected(device);
}
}
#Override
public void onServiceAdded(int status, BluetoothGattService service) {
super.onServiceAdded(status, service);
Log.d(TAG, "onServiceAdded() called with: status = [" + status + "], service = [" + service + "]");
listener.onServiceAdded();
}
#Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
Log.d(TAG, "onCharacteristicReadRequest() called with: device = [" + device + "], requestId = [" + requestId + "], offset = [" + offset + "], characteristic = [" + characteristic + "]");
listener.onReceive(device, characteristic);
}
#Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
Log.d(TAG, "onCharacteristicWriteRequest() called with: device = [" + device + "], requestId = [" + requestId + "], characteristic = [" + characteristic + "], preparedWrite = [" + preparedWrite + "], responseNeeded = [" + responseNeeded + "], offset = [" + offset + "], value = [" + value + "]");
}
#Override
public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
Log.d(TAG, "onDescriptorReadRequest() called with: device = [" + device + "], requestId = [" + requestId + "], offset = [" + offset + "], descriptor = [" + descriptor + "]");
if (GattServerConfiguration.CCC_DESCRIPTOR_UUID.equals(descriptor.getUuid())) {
Log.d(TAG, "Config descriptor read");
byte[] returnValue;
if (connectedDevices.contains(device)) {
returnValue = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
} else {
returnValue = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
}
bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, returnValue);
} else {
Log.w(TAG, "Unknown descriptor read request");
bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null);
}
}
#Override
public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
Log.d(TAG, "onDescriptorWriteRequest() called with: device = [" + device + "], requestId = [" + requestId + "], descriptor = [" + descriptor + "], preparedWrite = [" + preparedWrite + "], responseNeeded = [" + responseNeeded + "], offset = [" + offset + "], value = [" + value + "]");
if (GattServerConfiguration.CCC_DESCRIPTOR_UUID.equals(descriptor.getUuid())) {
Log.d(TAG, "Config descriptor read");
byte[] returnValue;
if (connectedDevices.contains(device)) {
returnValue = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
} else {
returnValue = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
}
bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, returnValue);
} else {
Log.w(TAG, "Unknown descriptor read request");
bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null);
}
}
#Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
super.onExecuteWrite(device, requestId, execute);
Log.d(TAG, "onExecuteWrite() called with: device = [" + device + "], requestId = [" + requestId + "], execute = [" + execute + "]");
}
#Override
public void onNotificationSent(BluetoothDevice device, int status) {
super.onNotificationSent(device, status);
Log.d(TAG, "onNotificationSent() called with: device = [" + device + "], status = [" + status + "]");
}
#Override
public void onMtuChanged(BluetoothDevice device, int mtu) {
super.onMtuChanged(device, mtu);
Log.d(TAG, "onMtuChanged() called with: device = [" + device + "], mtu = [" + mtu + "]");
}
#Override
public void onPhyUpdate(BluetoothDevice device, int txPhy, int rxPhy, int status) {
super.onPhyUpdate(device, txPhy, rxPhy, status);
Log.d(TAG, "onPhyUpdate() called with: device = [" + device + "], txPhy = [" + txPhy + "], rxPhy = [" + rxPhy + "], status = [" + status + "]");
}
#Override
public void onPhyRead(BluetoothDevice device, int txPhy, int rxPhy, int status) {
super.onPhyRead(device, txPhy, rxPhy, status);
Log.d(TAG, "onPhyRead() called with: device = [" + device + "], txPhy = [" + txPhy + "], rxPhy = [" + rxPhy + "], status = [" + status + "]");
}
};
private void startServer() {
bluetoothGattServer = bluetoothManager.openGattServer(applicationContext, gattCallback);
if (bluetoothGattServer == null) {
println("Server is null");
return;
}
bluetoothGattServer.addService(GattServerConfiguration.createGattService());
}
public void launch() {
if (isReady()) {
startServer();
startAdvertising();
}
}
private void stopAdvertising() {
if (bluetoothLeAdvertiser == null) return;
bluetoothLeAdvertiser.stopAdvertising(advertiseCallback);
}
private void stopServer() {
if (bluetoothGattServer == null) return;
bluetoothGattServer.close();
}
public void stop() {
stopAdvertising();
stopServer();
connectedDevices.clear();
}
private boolean isReady() {
if (bluetoothManager == null) {
return false;
}
return bluetoothAdapter.isEnabled() && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
private IGattServer listener;
public void setCallback(IGattServer listener) {
this.listener = listener;
}
}
Above code, successfully starts advertisement,
Another device successfully receive device in LE Scan (Using UUID's filter)
But connectGatt() not providing any callback.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
bluetoothGatt = bluetoothDevice.connectGatt(
getApplicationContext(), true, gattCallback,
BluetoothDevice.TRANSPORT_LE
);
} else {
bluetoothGatt = bluetoothDevice.connectGatt(getApplicationContext(), true, gattCallback);
}
Gatt Callback Sample Code.
private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
writeLog("onConnectionStateChange() called with: gatt = [" + gatt + "], status = [" + status + "], newState = [" + newState + "]");
broadcastUpdate(
ACTION_GATT_MESSAGE,
"onConnectionStateChange() called with: gatt = $gatt, status = $status, newState = $newState"
);
if (status == 8) {
writeLog("BLE Out Of Range");
broadcastUpdate(ACTION_GATT_MESSAGE, "BLE Out Of Range status == 8");
} else if (status == 19) {
writeLog("BLE Disconnected By Device");
broadcastUpdate(ACTION_GATT_MESSAGE, "BLE Disconnected By Device status == 19");
} else if (status == 22) {
writeLog("BLE Issue with bond");
broadcastUpdate(ACTION_GATT_MESSAGE, "BLE Issue with bond status == 22");
} else if (status == 133 || status == 62) {
writeLog("BLE Device not found");
broadcastUpdate(
ACTION_GATT_MESSAGE,
"BLE Device not found status == 133 || status == 62"
);
disconnect();
close();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
connectDevice(bluetoothAdapter.getRemoteDevice(PrefManager.getInstance(getApplicationContext()).getLeAddress()));
return;
}
if (newState == BluetoothProfile.STATE_CONNECTED) {
connected = true;
broadcastUpdate(ACTION_GATT_CONNECTED);
bluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
connected = false;
broadcastUpdate(ACTION_GATT_DISCONNECTED);
stopSelf();
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
writeLog("onServicesDiscovered() called with: gatt = [" + gatt + "], status = [" + status + "]");
if (status == BluetoothGatt.GATT_SUCCESS) {
Intent intent = new Intent(ACTION_GATT_SERVICES_DISCOVERED);
ArrayList<BluetoothGattService> services = new ArrayList<BluetoothGattService>();
for (BluetoothGattService gattService : gatt.getServices()) {
services.add(gattService);
}
intent.putParcelableArrayListExtra("services", services);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastUpdate(intent);
} else {
broadcastUpdate(ACTION_GATT_NO_SERVICES_DISCOVERED);
}
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
Log.e(
TAG,
"onCharacteristicRead() called with: gatt = $gatt, characteristic = $characteristic, status = $status"
);
if (status == BluetoothGatt.GATT_SUCCESS) {
Intent intent = new Intent(ACTION_DATA_AVAILABLE);
intent.putExtra("bytes", characteristic.getValue());
//lintent.putExtra("data", characteristic.getValue().toString());
broadcastUpdate(intent);
}
}
#Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
Log.e(
TAG,
"onCharacteristicWrite() called with: gatt = " + gatt + ", characteristic = " + characteristic + ", status = " + status
);
if (canceled || !connected || writeCharacteristic == null) {
writeLog("Return Form write 1");
return;
}
if (status != BluetoothGatt.GATT_SUCCESS) {
writeLog("Return Form write 2");
broadcastUpdate(ACTION_DATA_WRITE_FAIL);
return;
}
if (canceled) return;
writeLog("Write Success Checking for next bytes");
if (characteristic.getUuid().toString().equals(writeCharacteristic.getUuid().toString())) { // NOPMD - test object identity
writeNext();
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
Log.e(
TAG,
"onCharacteristicChanged() called with: gatt = $gatt, characteristic = $characteristic"
);
if (characteristic.getUuid().toString().equals(readCharacteristic.getUuid().toString())) {
Intent intent = new Intent(ACTION_DATA_AVAILABLE);
intent.putExtra("bytes", characteristic.getValue());
broadcastUpdate(intent);
}
}
#Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorRead(gatt, descriptor, status);
Log.e(
TAG,
"onDescriptorRead() called with: gatt = $gatt, descriptor = $descriptor, status = $status"
);
}
#Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
writeLog("onDescriptorWrite() called with: gatt = [" + gatt + "], descriptor = [" + descriptor + "], status = [" + status + "]");
}
#Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
super.onReliableWriteCompleted(gatt, status);
writeLog("onReliableWriteCompleted() called with: gatt = [" + gatt + "], status = [" + status + "]");
}
#Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
writeLog("onReadRemoteRssi() called with: gatt = [" + gatt + "], rssi = [" + rssi + "], status = [" + status + "]");
}
#Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
super.onMtuChanged(gatt, mtu, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
payloadSize = mtu - 3;
writeLog("payload size $payloadSize");
}
enableTxNotification();
}
#Override
public void onServiceChanged(#NonNull BluetoothGatt gatt) {
super.onServiceChanged(gatt);
}
};
I solved connection issue by.
bluetoothGatt = bluetoothDevice.connectGatt(
getApplicationContext(), false, gattCallback,
BluetoothDevice.TRANSPORT_AUTO
);

Not entering onCharacteristicRead or onCharacteristicChanged

As the title states my code seems to get stuck after onServicesDiscovered, the only reason i know this is that I have Log messages denoting so. Can anyone reveal what is wrong with my code? I can connect to my device but I am not receiving the data from it. I know its on my apps side because ive used the adafruit bluefruit app and the nRF app and they both receive the data.
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
Log.i("onConnectionStateChange", "State Changed from: " + status + " to " + newState);
gatt.discoverServices();
// seems to connect but if statements dont work?
// if (newState == BluetoothProfile.STATE_CONNECTED){ // 2
// Toast.makeText(BluetoothDiscovery.this, "Attempting service discovery", Toast.LENGTH_SHORT).show();
// Log.i("onConnectionStateChange", "Attempting service discovery: " + mGatt.discoverServices());
//// mGatt.discoverServices();
// } else if (newState == BluetoothProfile.STATE_DISCONNECTED){ // 0
// Toast.makeText(BluetoothDiscovery.this, "Connection has been terminated", Toast.LENGTH_SHORT).show();
// } else if (newState == BluetoothProfile.STATE_CONNECTING) { // 1
// Log.i("Welp", "IM GIVIN ER ALL SHES GOT CAPN");
// } else if (newState == BluetoothProfile.STATE_DISCONNECTING) { // 3
// Log.i("Welp", "HOW DID WE GET HERE");
// }
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status){
super.onServicesDiscovered(gatt, status);
Log.i("onServicesDiscovered", "Hey, we found a service");
List<BluetoothGattService> services = gatt.getServices();
Log.i("SERVICE", "Services: " + services.toString());
//BluetoothGattCharacteristic characteristic = services.get(4).getCharacteristics().get(0);
BluetoothGattCharacteristic characteristic = gatt.getService(baseUUID).getCharacteristic(rxUUID);
if (characteristic != null){
gatt.setCharacteristicNotification(characteristic, true);
}
List<BluetoothGattDescriptor> describeMe = characteristic.getDescriptors();
Log.i("DESCRIPTORS", "Descriptors: " + describeMe.toString());
Log.i("DESCRIPTORS", "Descriptors: " + describeMe.get(1).getUuid().toString());
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(describeMe.get(1).getUuid());
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
Log.i("ByeSERVICESDISCOVERED", "that");
}

How to write data to characteristic on button click?

I am making an android app that uses BLE. I am trying to write data to a characteristic on button click but unable to do that.
I have a service which is having two characteristic and out of those two characteristic I am writing data on one on button click.
Ble class where I have defined writeDatatoCharacteristic
/* set new value for particular characteristic */
public void writeDataToCharacteristic(final BluetoothGattCharacteristic ch, final byte[] value) {
if (mBluetoothAdapter == null || mBluetoothGatt == null || ch == null) {
return;
}
// first set it locally....
ch.setValue(value);
// ... and then "commit" changes to the peripheral
mBluetoothGatt.writeCharacteristic(ch);
}
xml file for button
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButtonPlay"
android:src="#drawable/play"
android:background="#android:color/transparent"
android:layout_alignTop="#+id/ivRestart"
android:layout_centerHorizontal="true"
android:onClick="onClickWrite"/>
Main Activity where I am calling the write data to characteristic function
public class Tens_modes extends AppCompatActivity {
private final String LOGTAG = "BLETEST";
private final String TARGET = "CC2650 SensorTag";
private BleWrapper mBleWrapper = null;
private mSensorState mState;
private String gattList = "";
private TextView mTv;
private enum mSensorState {IDLE, ACC_ENABLE, ACC_READ};
public final static UUID
UUID_ACC_SERV = fromString("FFE0"),
UUID_ACC_DATA = fromString("f000aa11-0451-4000-b000-000000000000"),
UUID_ACC_CONF = fromString("FFE9"), // 0: disable, 1: enable
UUID_ACC_PERI = fromString("f000aa13-0451-4000-b000-000000000000"); // Period in tens of milliseconds
private ImageButton play;
private ImageButton pause;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tens_modes);
play = (ImageButton)findViewById(R.id.imageButtonPlay);
pause = (ImageButton)findViewById(R.id.imageButtonPause);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play.setVisibility(View.INVISIBLE);
pause.setVisibility(View.VISIBLE);
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pause.setVisibility(View.INVISIBLE);
play.setVisibility(View.VISIBLE);
//Ble stuff
mBleWrapper = new BleWrapper(this, new BleWrapperUiCallbacks.Null()
{
#Override
public void uiDeviceFound(final BluetoothDevice device, final int rssi, final byte[] record)
{
Log.d(LOGTAG, "uiDeviceFound: " + device.getName() + ", " + rssi + ", " + record.toString());
if (device.getName().equals(TARGET))
{
if (!mBleWrapper.connect(device.getAddress()))
{
Log.d(LOGTAG, "uiDeviceFound: Problem connecting to remote device.");
}
}
//stopScan();
}
#Override
public void uiDeviceConnected(BluetoothGatt gatt, BluetoothDevice device)
{
Log.d(LOGTAG, "uiDeviceConnected: State = " + mBleWrapper.getAdapter().getState());
}
#Override
public void uiDeviceDisconnected(BluetoothGatt gatt, BluetoothDevice device) {
Log.d(LOGTAG, "uiDeviceDisconnected: State = " + mBleWrapper.getAdapter().getState());
}
#Override
public void uiAvailableServices(BluetoothGatt gatt, BluetoothDevice device, List<BluetoothGattService> services)
{
BluetoothGattCharacteristic c;
BluetoothGattDescriptor d;
for (BluetoothGattService service : services)
{
String serviceName = BleNamesResolver.resolveUuid(service.getUuid().toString());
Log.e(LOGTAG, serviceName);
gattList += serviceName + "\n";
mBleWrapper.getCharacteristicsForService(service);
}
// enable services
Log.e(LOGTAG, "uiAvailableServices: Enabling services");
c = gatt.getService(UUID_ACC_SERV).getCharacteristic(UUID_ACC_CONF);
mBleWrapper.writeDataToCharacteristic(c, new byte[] {0300000000AA});
//mState = mSensorState.ACC_ENABLE;
// set notification on characteristic
//Log.d(LOGTAG, "uiAvailableServices: Setting notification");
//c = gatt.getService(UUID_IRT_SERV).getCharacteristic(UUID_IRT_DATA);
//mBleWrapper.setNotificationForCharacteristic(c, true);
// enable notification on descriptor
//d = c.getDescriptor(UUID_CCC_DESC);
//d.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
//gatt.writeDescriptor(d);
}
#Override
public void uiCharacteristicForService( BluetoothGatt gatt,
BluetoothDevice device,
BluetoothGattService service,
List<BluetoothGattCharacteristic> chars)
{
super.uiCharacteristicForService(gatt, device, service, chars);
for (BluetoothGattCharacteristic c : chars)
{
String charName = BleNamesResolver.resolveCharacteristicName(c.getUuid().toString());
Log.d(LOGTAG, charName);
gattList += "Characteristic: " + charName + "\n";
}
}
#Override
public void uiSuccessfulWrite( BluetoothGatt gatt,
BluetoothDevice device,
BluetoothGattService service,
BluetoothGattCharacteristic ch,
String description)
{
BluetoothGattCharacteristic c;
super.uiSuccessfulWrite(gatt, device, service, ch, description);
Log.d(LOGTAG, "uiSuccessfulWrite");
switch (mState)
{
case ACC_ENABLE:
Log.d(LOGTAG, "uiSuccessfulWrite: Reading acc");
c = gatt.getService(UUID_ACC_SERV).getCharacteristic(UUID_ACC_DATA);
mBleWrapper.requestCharacteristicValue(c);
mState = mSensorState.ACC_READ;
break;
case ACC_READ:
Log.d(LOGTAG, "uiSuccessfulWrite: state = ACC_READ");
break;
default:
break;
}
}
#Override
public void uiFailedWrite( BluetoothGatt gatt,
BluetoothDevice device,
BluetoothGattService service,
BluetoothGattCharacteristic ch,
String description)
{
super.uiFailedWrite(gatt, device, service, ch, description);
Log.d(LOGTAG, "uiFailedWrite");
}
#Override
public void uiNewValueForCharacteristic(BluetoothGatt gatt,
BluetoothDevice device,
BluetoothGattService service,
BluetoothGattCharacteristic ch,
String strValue,
int intValue,
byte[] rawValue,
String timestamp)
{
super.uiNewValueForCharacteristic(gatt, device, service, ch, strValue, intValue, rawValue, timestamp);
Log.d(LOGTAG, "uiNewValueForCharacteristic");
for (byte b:rawValue)
{
Log.d(LOGTAG, "Val: " + b);
}
}
#Override
public void uiGotNotification( BluetoothGatt gatt,
BluetoothDevice device,
BluetoothGattService service,
BluetoothGattCharacteristic characteristic)
{
super.uiGotNotification(gatt, device, service, characteristic);
String ch = BleNamesResolver.resolveCharacteristicName(characteristic.getUuid().toString());
Log.d(LOGTAG, "uiGotNotification: " + ch);
}
});
}
public void onClickWrite(View v){
if(mBleWrapper != null) {
// enable services
Log.e(LOGTAG, "uiAvailableServices: Enabling services");
byte[] value = new byte[1];
value[0] = (byte)21;
mBleWrapper.writeDataToCharacteristic(UUID_ACC_CONF, new byte[] {0300000000AA});
}
}
I want to write 0300000000AA as a value to characteristic but don't know how to do that. Searching for it from last 4,5 hours but didn;t get anything useful
Please if anyone can help me with this and tell me what I am doing wrong
Thanks
This should do it for you. (well be a start, I'm not sure about encoding)
byte[] temp;
//This will at least compile, however I don't know if that is what you want, strings in java are unicode, not ascii. you might have to convert to your desired encoding
temp = "0300000000AA".getBytes();
mBleWrapper.writeDataToCharacteristic(UUID_ACC_CONF, temp );

How do I connect to multiple Wifi networks one after the another programatically in Android?

I want to check the presence of some pre-defined open Wifi networks using the Android API (and I want to add them programatically before checking their presence). Here's what I've done. I have created a blank Activity as follows:
WifiManager wifiManager;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
myWifis();
}
public void myWifis() {
//Add first network
wcOne = new WifiConfiguration();
wcOne.SSID = "\"" + networkOne + "\"";
wcOne.status = WifiConfiguration.Status.ENABLED;
wcOne.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//Get Network ID from the wifiManager Object
netOneId = wifiManager.addNetwork(wcOne);
if (networkOneId != -1) {
networkOnePresent = wifiManager.enableNetwork(wcOne.networkId, true);
}
//Add second network
wcTwo = new WifiConfiguration();
wcTwo.SSID = "\"" + networkTwo + "\"";
wcTwo.status = WifiConfiguration.Status.ENABLED;
wcTwo.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//Get Network ID from the wifiManager Object
netTwoId = mainWifiObj.addNetwork(wcTwo);
if (netTwoId != -1) {
networkTwoPresent = mainWifiObj.enableNetwork(wcTwo.networkId, true);
}
if(networkOnePresent && networkTwoPresent)
createAlert(true);
else
createAlert(false);
wifiManager.disconnect();
wifiManager.removeNetwork(wcOne.networkId);
wifiManager.removeNetwork(wcTwo.networkId);
}
public void createAlert(boolean bothNetworksPresent){
if(bothNetworksPresent){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Both networks present")
.setMessage("Both networks present")
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
}
});
AlertDialog dialog = alertDialog.create();
dialog.show();
}
else{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Not Present")
.setMessage("Not Present")
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
}
});
AlertDialog dialog = alertDialog.create();
dialog.show();
}
}
.
I see that both the networks get added to my Wifi list however I get a message "Not present". This is strange because when I go to the Android's Wifi menu, I initially don't see the Wifi being present but when I hit scan I see those networks.
I want to check if I can connect to both the Wifi hotspots. I want connect to one hotspot disconnect and then connect to another one. How do I do this?
Edit:
I also note that the Wifi networks that I add are not being removed from the list. Is there any particular reason for this?
Edit 2
I even tried changing my entire code to listen to BroadcastReceiver for scan and connection separately and that too after certain intervals of time. So here's what I did:
WifiManager wifiManager;
private final Handler mHandler = new Handler();
public final String TAG = "myWifiScanner";
boolean isOneAdded = false, isTwoAdded = false, isThreeAdded = false;
boolean isOneConnected = false, isTwoConnected = false, isThreeConnected = false;
boolean isOneEnabled = false, isTwoEnabled = false, isThreeEnabled = false;
IntentFilter iFScan, iFConnect;
List<ScanResult> scanList;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
checkConnections();
}
private void receiverMethod(){
//iFScan = new IntentFilter();
iFConnect = new IntentFilter();
iFConnect.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
iFConnect.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
//registerReceiver(scanR, iFScan);
registerReceiver(connectR, iFConnect);
wifiManager.startScan();
Log.d(TAG, "\nScan started\n");
}
private final BroadcastReceiver connectR = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
if(intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)){
String ssid = null;
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(netInfo.isConnected()){
final WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if(connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())){
ssid = connectionInfo.getSSID();
if(isOneAdded && ssid.equals(networkOne)){
isOneConnected = true;
Log.d(TAG, "One Connected\n");
}
if(isTwoAdded && ssid.equals(networkTwo)){
isTwoConnected = true;
Log.d(TAG, "Two Connected\n");
}
if(isThreeAdded && ssid.equals(networkThree)){
isThreeConnected = true;
Log.d(TAG, "Three Connected\n");
}
}
}
}
if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
scanList = wifiManager.getScanResults();
for(int i = 0; i < scanList.size(); i++){
if(isOneAdded && scanList.get(i).toString().contains(networkOne)){
isOneEnabled = true;
Log.d(TAG, "One Enabled\n");
}
if(isTwoAdded && scanList.get(i).toString().contains(networkTwo)){
isTwoEnabled = true;
Log.d(TAG, "Two Enabled\n");
}
if(isThreeAdded && scanList.get(i).toString().contains(networkThree)){
isThreeEnabled = true;
Log.d(TAG, "Three Enabled\n");
}
}
}
}
};
public final Runnable addNetworkOne = new Runnable() {
#Override
public void run() {
//Add first network
wcOne = new WifiConfiguration();
wcOne.SSID = "\"" + networkOne + "\"";
wcOne.status = WifiConfiguration.Status.ENABLED;
wcOne.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//Get Network ID from the wifiManager Object
netOneId = wifiManager.addNetwork(wcOne);
if (networkOneId != -1) {
networkOnePresent = wifiManager.enableNetwork(wcOne.networkId, true);
}
}
isOneAdded = true
receiverMethod();
};
public final Runnable addNetworkTwo = new Runnable() {
#Override
public void run() {
//Add second network
wcTwo = new WifiConfiguration();
wcTwo.SSID = "\"" + networkTwo + "\"";
wcTwo.status = WifiConfiguration.Status.ENABLED;
wcTwo.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//Get Network ID from the wifiManager Object
netTwoId = wifiManager.addNetwork(wcTwo);
if (netTwoId != -1) {
networkTwoPresent = wifiManager.enableNetwork(wcTwo.networkId, true);
}
}
isTwoAdded = true
receiverMethod();
};
public final Runnable addNetworkThree = new Runnable() {
#Override
public void run() {
//Add three network
wcThree = new WifiConfiguration();
wcThree.SSID = "\"" + networkThree + "\"";
wcThree.status = WifiConfiguration.Status.ENABLED;
wcThree.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//Get Network ID from the wifiManager Object
netThreeId = wifiManager.addNetwork(wcTwo);
if (netThreeId != -1) {
networkThreePresent = wifiManager.enableNetwork(wcThree.networkId, true);
}
}
isThreeAdded = true
receiverMethod();
};
public final Runnable areAllWifisPresent = new Runnable() {
#Override
public void run() {
if(isOneEnabled && isTwoEnabled && isThreeeEnabled){
if(isOneConnected && isTwoConnected && isThreeConnected){
Log.d(TAG, "All three Wifis are present.");
}
}
};
public void checkConnections() {
mHandler.postDelayaed(addNetworkOne, 10*1000);
mHandler.postDelayed(addNetworkTwo, 20*1000);
mHandler.postDelayed(addNetworkThree, 30*1000);
mHandler.postDelayed(areAllWifisPresent, 40*1000);
//wifiManager.disconnect();
//wifiManager.removeNetwork(wcOne.networkId);
//wifiManager.removeNetwork(wcTwo.networkId);
//wifiManager.removeNetwork(wcThree.networkId);
}
**Edit 3: **
I also noticed that the receiver for checking if Wifi is connected is not getting called. I am not sure why.
Please change your MyWifi() method to
public void myWifis() {
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
//Add first network
wcOne = new WifiConfiguration();
wcOne.SSID = "\""+SSID+"\"";
wcOne.status = WifiConfiguration.Status.ENABLED;
wcOne.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//Get Network ID from the MainWiFi Object
int netOneId = mainWifiObj.addNetwork(wcOne);
boolean networkOnePresent = false;
//this way we will enable wifi network.
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
Log.d("wifi", "wifi SSID is = "+i.SSID);
if(i.SSID != null && i.SSID.equals("\"" + SSID + "\"")) {
wifiManager.disconnect();
networkOnePresent = wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
Log.d("wifi", "net id is = "+netOneId);
break;
}
}
if(networkOnePresent)
createAlert(true);
else
createAlert(false);
}
It will work.

Categories