Not Connecting Gatt Server - java

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
);

Related

int android.database.Cursor.getColumnIndex(java.lang.String)' on a null object reference

public class MainActivity extends AppCompatActivity {
TextView dataTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataTextView = findViewById(R.id.dataTextView);
FloatingActionButton floatingActionButton = findViewById(R.id.floatingActionButton);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, add_member.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
displayData();
}
private void displayData () {
String [] projection = {
MemberEntry._ID,
MemberEntry.COLUMN_FIRST_NAME,
MemberEntry.COLUMN_LAST_NAME,
MemberEntry.COLUMN_GENDER,
MemberEntry.COLUMN_SPORT
};
Cursor cursor = getContentResolver().query(
MemberEntry.CONTENT_URI,
projection,
null,
null,
null
);
dataTextView.setText("All members\n\n");
dataTextView.append(MemberEntry._ID + " " +
MemberEntry.COLUMN_FIRST_NAME + " " +
MemberEntry.COLUMN_LAST_NAME + " " +
MemberEntry.COLUMN_GENDER + " " +
MemberEntry.COLUMN_SPORT);
int idIndex = cursor.getColumnIndex(MemberEntry._ID);
int idFirstName = cursor.getColumnIndex(MemberEntry.COLUMN_LAST_NAME);
int idLastName = cursor.getColumnIndex(MemberEntry.COLUMN_LAST_NAME);
int idGender = cursor.getColumnIndex(MemberEntry.COLUMN_GENDER);
int idSport = cursor.getColumnIndex(MemberEntry.COLUMN_SPORT);
while (cursor.moveToNext()) {
int currentID = cursor.getInt(idIndex);
String currentFirstName = cursor.getString(idFirstName);
String currentLastName = cursor.getString(idLastName);
int currentGender = cursor.getInt(idGender);
String currentSport = cursor.getString(idSport);
dataTextView.append("\n" +
currentID + " " +
currentFirstName + " " +
currentLastName + " " +
currentGender + " " +
currentSport);
}
cursor.close();
}
}
This throws an exception:
java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndex(java.lang.String)' on a null object reference
at com.example.sportclub.MainActivity.displayData(MainActivity.java:66)
at com.example.sportclub.MainActivity.onStart(MainActivity.java:40)
can you help me ?)
It looks like the line cursor.getColumnIndex(MemberEntry._ID); is the problem. In all likelihood given the error message cursor is null and that your call to getContentResolver().query failed.
private void insertMember () {
String firstName = firstNameEditText.getText().toString().trim();
String lastName = lastNameEditText.getText().toString().trim();
String sport = sportEditText.getText().toString().trim();
ContentValues contentValues = new ContentValues();
contentValues.put(MemberEntry.COLUMN_FIRST_NAME, firstName);
contentValues.put(MemberEntry.COLUMN_LAST_NAME, lastName);
contentValues.put(MemberEntry.COLUMN_SPORT, sport);
contentValues.put(MemberEntry.COLUMN_GENDER, gender);
ContentResolver contentResolver = getContentResolver();
Uri uri = contentResolver.insert(MemberEntry.CONTENT_URI, contentValues);
if (uri == null ) {
Toast.makeText(this, "Insertion of data in the table failed for ", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Data save ", Toast.LENGTH_LONG).show();
}
}
}
this is correct code ? or not ?

How to call inbuilt method of location listener in another class

I am using location listener to track the location.I implement the location listener, there are inbuilt methods of location listener such as onLocationChanged,OnstatusChanged,onProviderEnabled etc.Whenerver the location changed it will hit on server but I want to do at every 10 min of interval So I am using timer for that after every 10 mins it will hit the location. I cannot call the method inside the timer. So how to do it.
public class LocationMonitoringService implements LocationListener, GpsStatus.Listener {
private static final String TAG = LocationMonitoringService.class.getSimpleName();
private final Context mContext;
private final LocationRepository mLocationRepository;
private final ShareLocationAdapterClass mAdapter;
private final SyncOfflineRepository syncOfflineRepository;
private long updatedTime = 0;
private final List<UserLocationPojo> mUserLocationPojoList;
private final SyncOfflineAttendanceRepository syncOfflineAttendanceRepository;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000 * 60 * 5;
public LocationMonitoringService(final Context context) {
mContext = context;
mLocationRepository = new LocationRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineRepository = new SyncOfflineRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineAttendanceRepository = new SyncOfflineAttendanceRepository(AUtils.mainApplicationConstant.getApplicationContext());
mUserLocationPojoList = new ArrayList<>();
mAdapter = new ShareLocationAdapterClass();
mAdapter.setShareLocationListener(new ShareLocationAdapterClass.ShareLocationListener() {
#Override
public void onSuccessCallBack(boolean isAttendanceOff) {
if (isAttendanceOff && !syncOfflineAttendanceRepository.checkIsAttendanceIn()) {
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
}
}
#Override
public void onFailureCallBack() {
}
});
}
public void onStartTacking() {
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
//Exception thrown when GPS or Network provider were not available on the user's device.
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(false);
criteria.setBearingRequired(false);
//API level 9 and up
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
int gpsFreqInDistance =100;
assert locationManager != null;
locationManager.addGpsStatusListener(this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
} catch (IllegalArgumentException | SecurityException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
Log.d(TAG, "onStartTacking: " + e.getLocalizedMessage());
e.printStackTrace();
} catch (RuntimeException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
e.printStackTrace();
}
}
public void onStopTracking(Context context) {
mAdapter.shareLocation();
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
// cancelAlarm(context, (AlarmManager)context.getSystemService(Context.ALARM_SERVICE));
}
/*
* LOCATION CALLBACKS
*/
//to get the location change
#Override
public void onLocationChanged(Location location) {
Log.d("okh ", "onLocationChanged: "+System.currentTimeMillis());
if (location != null) {
Log.d(TAG, String.valueOf(location.getAccuracy()));
if (!AUtils.isNullString(String.valueOf(location.getLatitude())) && !AUtils.isNullString(String.valueOf(location.getLongitude()))) {
Prefs.putString(AUtils.LAT, String.valueOf(location.getLatitude()));
Prefs.putString(AUtils.LONG, String.valueOf(location.getLongitude()));
if (Prefs.getBoolean(AUtils.PREFS.IS_ON_DUTY, false)) {
if (updatedTime == 0) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
if ((updatedTime + AUtils.LOCATION_INTERVAL_MINUTES) <= System.currentTimeMillis()) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5,notify_interval);
// sendLocation();
}
}
} else {
Log.d(TAG, "onLocationChanged: no location found !!");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged" + provider + "Status" + status);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, " onProviderEnabled" + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, " onProviderDisabled" + provider);
}
#Override
public void onGpsStatusChanged(int event) {
}
private void sendLocation() {
// mAdapter.shareLocation(getTempList());
Log.d("okh", "sendLocation: Current Time In Millies "+ System.currentTimeMillis());
try {
Calendar CurrentTime = AUtils.getCurrentTime();
Calendar DutyOffTime = AUtils.getDutyEndTime();
if (CurrentTime.before(DutyOffTime)) {
Log.i(TAG, "Before");
UserLocationPojo userLocationPojo = new UserLocationPojo();
userLocationPojo.setUserId(Prefs.getString(AUtils.PREFS.USER_ID, ""));
userLocationPojo.setLat(Prefs.getString(AUtils.LAT, ""));
userLocationPojo.setLong(Prefs.getString(AUtils.LONG, ""));
double startLat = Double.parseDouble(Prefs.getString(AUtils.LAT, "0"));
double startLng = Double.parseDouble(Prefs.getString(AUtils.LONG, "0"));
userLocationPojo.setDistance(String.valueOf(AUtils.calculateDistance(
AUtils.mainApplicationConstant.getApplicationContext(), startLat, startLng)));
// userLocationPojo.setDatetime(AUtils.getServerDateTime()); //TODO
userLocationPojo.setDatetime(AUtils.getServerDateTimeLocal());
userLocationPojo.setOfflineId("0");
userLocationPojo.setIsOffline(AUtils.isInternetAvailable() && AUtils.isConnectedFast(mContext));
String UserTypeId = Prefs.getString(AUtils.PREFS.USER_TYPE_ID, AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI);
if (AUtils.isInternetAvailable()) {
TableDataCountPojo.LocationCollectionCount count = syncOfflineRepository.getLocationCollectionCount(AUtils.getLocalDate());
if ((UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI) || UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_WASTE_MANAGER))
&& (count.getLocationCount() > 0 || count.getCollectionCount() > 0)) {
syncOfflineRepository.insetUserLocation(userLocationPojo);
} else {
mUserLocationPojoList.add(userLocationPojo);
mAdapter.shareLocation(mUserLocationPojoList);
mUserLocationPojoList.clear();
}
} else {
if (UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_EMP_SCANNIFY)) {
Type type = new TypeToken<UserLocationPojo>() {
}.getType();
mLocationRepository.insertUserLocationEntity(new Gson().toJson(userLocationPojo, type));
} else {
syncOfflineRepository.insetUserLocation(userLocationPojo);
}
mUserLocationPojoList.clear();
}
}
else {
Log.i(TAG, "After");
syncOfflineAttendanceRepository.performCollectionInsert(mContext,
syncOfflineAttendanceRepository.checkAttendance(), AUtils.getCurrentDateDutyOffTime());
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
Activity activity = ((Activity) AUtils.currentContextConstant);
if (activity instanceof DashboardActivity) {
((Activity) AUtils.currentContextConstant).recreate();
AUtils.DutyOffFromService = true;
}
if (!AUtils.isNull(AUtils.currentContextConstant)) {
((Activity) AUtils.currentContextConstant).recreate();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class TimerTaskToGetLocation extends TimerTask {
#Override
public void run() {
sendLocation();
}
}
}
Here is the code please try this:
public class LocationMonitoringService implements LocationListener, GpsStatus.Listener {
private static final String TAG = LocationMonitoringService.class.getSimpleName();
private final Context mContext;
private final LocationRepository mLocationRepository;
private final ShareLocationAdapterClass mAdapter;
private final SyncOfflineRepository syncOfflineRepository;
private long updatedTime = 0;
private int gpsFreqInDistance =100;
private LocationManager locationManager;
private final List<UserLocationPojo> mUserLocationPojoList;
private final SyncOfflineAttendanceRepository syncOfflineAttendanceRepository;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000 * 60 * 5;
public LocationMonitoringService(final Context context) {
mContext = context;
// here we declare the variable as a field for this class instance
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
mLocationRepository = new LocationRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineRepository = new SyncOfflineRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineAttendanceRepository = new SyncOfflineAttendanceRepository(AUtils.mainApplicationConstant.getApplicationContext());
mUserLocationPojoList = new ArrayList<>();
mAdapter = new ShareLocationAdapterClass();
mAdapter.setShareLocationListener(new ShareLocationAdapterClass.ShareLocationListener() {
#Override
public void onSuccessCallBack(boolean isAttendanceOff) {
if (isAttendanceOff && !syncOfflineAttendanceRepository.checkIsAttendanceIn()) {
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
}
}
#Override
public void onFailureCallBack() {
}
});
}
public void onStartTacking() {
//Exception thrown when GPS or Network provider were not available on the user's device.
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(false);
criteria.setBearingRequired(false);
//API level 9 and up
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
assert locationManager != null;
locationManager.addGpsStatusListener(this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
} catch (IllegalArgumentException | SecurityException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
Log.d(TAG, "onStartTacking: " + e.getLocalizedMessage());
e.printStackTrace();
} catch (RuntimeException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
e.printStackTrace();
}
}
public void onStopTracking(Context context) {
mAdapter.shareLocation();
// removed initialization from here
locationManager.removeUpdates(this);
// cancelAlarm(context, (AlarmManager)context.getSystemService(Context.ALARM_SERVICE));
}
/*
* LOCATION CALLBACKS
*/
//to get the location change
#Override
public void onLocationChanged(Location location) {
Log.d("okh ", "onLocationChanged: "+System.currentTimeMillis());
if (location != null) {
Log.d(TAG, String.valueOf(location.getAccuracy()));
if (!AUtils.isNullString(String.valueOf(location.getLatitude())) && !AUtils.isNullString(String.valueOf(location.getLongitude()))) {
Prefs.putString(AUtils.LAT, String.valueOf(location.getLatitude()));
Prefs.putString(AUtils.LONG, String.valueOf(location.getLongitude()));
if (Prefs.getBoolean(AUtils.PREFS.IS_ON_DUTY, false)) {
if (updatedTime == 0) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
if ((updatedTime + AUtils.LOCATION_INTERVAL_MINUTES) <= System.currentTimeMillis()) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5,notify_interval);
// sendLocation();
}
}
} else {
Log.d(TAG, "onLocationChanged: no location found !!");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged" + provider + "Status" + status);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, " onProviderEnabled" + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, " onProviderDisabled" + provider);
}
#Override
public void onGpsStatusChanged(int event) {
}
private void sendLocation() {
// mAdapter.shareLocation(getTempList());
Log.d("okh", "sendLocation: Current Time In Millies "+ System.currentTimeMillis());
try {
Calendar CurrentTime = AUtils.getCurrentTime();
Calendar DutyOffTime = AUtils.getDutyEndTime();
if (CurrentTime.before(DutyOffTime)) {
Log.i(TAG, "Before");
UserLocationPojo userLocationPojo = new UserLocationPojo();
userLocationPojo.setUserId(Prefs.getString(AUtils.PREFS.USER_ID, ""));
userLocationPojo.setLat(Prefs.getString(AUtils.LAT, ""));
userLocationPojo.setLong(Prefs.getString(AUtils.LONG, ""));
double startLat = Double.parseDouble(Prefs.getString(AUtils.LAT, "0"));
double startLng = Double.parseDouble(Prefs.getString(AUtils.LONG, "0"));
userLocationPojo.setDistance(String.valueOf(AUtils.calculateDistance(
AUtils.mainApplicationConstant.getApplicationContext(), startLat, startLng)));
// userLocationPojo.setDatetime(AUtils.getServerDateTime()); //TODO
userLocationPojo.setDatetime(AUtils.getServerDateTimeLocal());
userLocationPojo.setOfflineId("0");
userLocationPojo.setIsOffline(AUtils.isInternetAvailable() && AUtils.isConnectedFast(mContext));
String UserTypeId = Prefs.getString(AUtils.PREFS.USER_TYPE_ID, AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI);
if (AUtils.isInternetAvailable()) {
TableDataCountPojo.LocationCollectionCount count = syncOfflineRepository.getLocationCollectionCount(AUtils.getLocalDate());
if ((UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI) || UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_WASTE_MANAGER))
&& (count.getLocationCount() > 0 || count.getCollectionCount() > 0)) {
syncOfflineRepository.insetUserLocation(userLocationPojo);
} else {
mUserLocationPojoList.add(userLocationPojo);
mAdapter.shareLocation(mUserLocationPojoList);
mUserLocationPojoList.clear();
}
} else {
if (UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_EMP_SCANNIFY)) {
Type type = new TypeToken<UserLocationPojo>() {
}.getType();
mLocationRepository.insertUserLocationEntity(new Gson().toJson(userLocationPojo, type));
} else {
syncOfflineRepository.insetUserLocation(userLocationPojo);
}
mUserLocationPojoList.clear();
}
}
else {
Log.i(TAG, "After");
syncOfflineAttendanceRepository.performCollectionInsert(mContext,
syncOfflineAttendanceRepository.checkAttendance(), AUtils.getCurrentDateDutyOffTime());
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
Activity activity = ((Activity) AUtils.currentContextConstant);
if (activity instanceof DashboardActivity) {
((Activity) AUtils.currentContextConstant).recreate();
AUtils.DutyOffFromService = true;
}
if (!AUtils.isNull(AUtils.currentContextConstant)) {
((Activity) AUtils.currentContextConstant).recreate();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class TimerTaskToGetLocation extends TimerTask {
#Override
public void run() {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this,null);
}
}
}

Google Maps Direction API Android Studio - Adding an additional waypoint in between of the route

I am working on my project trying to add a waypoint in between of the route that I generated from my Location to Destination, short (point A to point B). I am not able to do this due to only a singular marker added to the calculateDirections() method and calculated.
How program works:
Location is added to the map, the first point is added when the user searches for the location in an autocomplete view and it gets calculated straight away showing the route to the user. Once this is done, user is able to click anywhere on the map to add an additional marker.
The problem:
Once the additional marker is added, the program just reroutes everything to the new point leaving the initial point. What can I do to fix this issue, here is the essential code for autocomplete method, calculate route and calculate popylines:
mSearchText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
Intent intent = new
Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY,
fields)
.build(MapsActivity.this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
hideSoftKeyboard();
return false;
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
String searchString = place.getName();
Geocoder geocoder = new Geocoder(MapsActivity.this,
Locale.getDefault());
List<Address> list;
try {
list = geocoder.getFromLocationName(searchString, 1);
if (list.size()> 0){
Address address = list.get(0);
LatLng latLng = new
LatLng(address.getLatitude(),address.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
MarkerOptions marker = new
MarkerOptions().position(latLng);
calculateDirections(marker);
//add on map click listener and add an additional marker
mMap.setOnMapClickListener(new
GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng latLng) {
List<LatLng> list = new ArrayList<>();
list.add(latLng);
// Add some markers to the map, and add a data
object to each marker
MarkerOptions marker2 = new
MarkerOptions().position(latLng);
calculateDirections(marker2);
}
});
}
} catch (IOException e) {
Log.e(TAG, "geoLocate: IOException: " + e.getMessage());
e.printStackTrace();
}
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
Status status = Autocomplete.getStatusFromIntent(data);
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
private void calculateDirections(MarkerOptions marker){
Log.d(TAG, "calculateDirections: calculating directions.");
ArrayList<MarkerOptions> markers = new ArrayList<>(2);
markers.add(marker);
for (int i = 0; i < markers.size(); i++) {
dest1 = markers.get(0);
com.google.maps.model.LatLng destination = new
com.google.maps.model.LatLng(
dest1.getPosition().latitude,
dest1.getPosition().longitude
);
if (markers.size() > 1){
dest2 = markers.get(1);
DirectionsApiRequest directions = new
DirectionsApiRequest(mGeoApiContext);
directions.alternatives(true);
directions.origin(
new com.google.maps.model.LatLng(
userPosition.getPosition().latitude,
userPosition.getPosition().longitude
)
);
directions.optimizeWaypoints(true);
directions.waypoints(
new com.google.maps.model.LatLng(
dest2.getPosition().latitude,
dest2.getPosition().longitude
)
);
Log.d(TAG, "calculateDirections: destination: " +
destination.toString());
directions.destination(destination).setCallback(new
PendingResult.Callback<DirectionsResult>() {
#Override
public void onResult(DirectionsResult result) {
Log.d(TAG, "calculateDirections: routes: " +
result.routes[0].toString());
Log.d(TAG, "calculateDirections: duration: " +
result.routes[0].legs[0].duration);
Log.d(TAG, "calculateDirections: distance: " +
result.routes[0].legs[0].distance);
Log.d(TAG, "calculateDirections: geocodedWayPoints: "
+ result.geocodedWaypoints[0].toString());
addPolylinesToMap(result);
}
#Override
public void onFailure(Throwable e) {
Log.e(TAG, "calculateDirections: Failed to get
directions: " + e.getMessage());
}
});
}
else {
DirectionsApiRequest directions = new
DirectionsApiRequest(mGeoApiContext);
directions.alternatives(true);
directions.origin(
new com.google.maps.model.LatLng(
userPosition.getPosition().latitude,
userPosition.getPosition().longitude
)
);
Log.d(TAG, "calculateDirections: destination: " +
destination.toString());
directions.destination(destination).setCallback(new
PendingResult.Callback<DirectionsResult>() {
#Override
public void onResult(DirectionsResult result) {
Log.d(TAG, "calculateDirections: routes: " +
result.routes[0].toString());
Log.d(TAG, "calculateDirections: duration: " +
result.routes[0].legs[0].duration);
Log.d(TAG, "calculateDirections: distance: " +
result.routes[0].legs[0].distance);
Log.d(TAG, "calculateDirections: geocodedWayPoints: "
+ result.geocodedWaypoints[0].toString());
addPolylinesToMap(result);
}
#Override
public void onFailure(Throwable e) {
Log.e(TAG, "calculateDirections: Failed to get
directions: " + e.getMessage());
}
});
}
}
}
private void addPolylinesToMap(final DirectionsResult result){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "run: result routes: " + result.routes.length);
//check if there are any polylines selected and remove the old
one before the new
//one is selected
if(mPolylinesData.size() > 0){
for (PolylineData polylineData: mPolylinesData){
polylineData.getPolyline().remove();
}
mPolylinesData.clear();
mPolylinesData = new ArrayList<>();
}
double duration = 999999;
for(DirectionsRoute route: result.routes){
Log.d(TAG, "run: leg: " + route.legs[0].toString());
// Get all the lines on checklist by calling decoder path
List<com.google.maps.model.LatLng> decodedPath =
PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());
// Adding new array list by adding all the lines
List<LatLng> newDecodedPath = new ArrayList<>();
// This loops through all the LatLng coordinates of ONE
polyline.
for(com.google.maps.model.LatLng latLng: decodedPath){
newDecodedPath.add(new LatLng(
latLng.lat,
latLng.lng
));
}
Polyline polyline = mMap.addPolyline(new
PolylineOptions().addAll(newDecodedPath));
polyline.setColor(ContextCompat.getColor(getApplicationContext(),
R.color.darkGrey));
polyline.setClickable(true);
mPolylinesData.add(new PolylineData(polyline,
route.legs[0]));
// Measure time in seconds of all trip durations and
select the shortest duration
double tempDuration = route.legs[0].duration.inSeconds;
if(tempDuration < duration){
duration = tempDuration;
onPolylineClick(polyline);
}
}
}
});
}

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");
}

Android BLE peripheral device data receiving

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?

Categories