#SuppressLint("MissingPermission") using is it harmful? - java

My code was giving an error
Overwriting this annotation fixed the error. Is this a healthy solution?
The class giving the error is related to bluetooth.
"Add permissions check" It gives an error when I do the suggestion.
Error:
Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException
Thanks
I used #SuppressLint("MissingPermission") but I couldn't trust
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
device, final String socketType) {
// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Cancel the accept thread because we only want to connect to one device
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket, socketType);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(BluetoothState.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(BluetoothState.DEVICE_NAME, device.getName());
bundle.putString(BluetoothState.DEVICE_ADDRESS, device.getAddress());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(BluetoothState.STATE_CONNECTED);
}

AFAIK, in order for MissingPermission error not to appear, you would have to check for the permission within the function.
Now, if you are absolutely certain, that the permission is, and will be, getting checked before the call of this function, it is OK to use #SuppressLint("MissingPermission"). What I would additionally do, is put a comment as to why you suppressed the error. Something in the line of: #SuppressLint("MissingPermission") // permission must be checked before the call of the function!.

Related

RxAndroidBLE already connected and can't send data to IoT device

I have an IoT device with BLE on it and also I have a smartphone which support BLE protocol.
I am using RxAndroidBle: com.polidea.rxandroidble2:rxandroidble:1.11.1
The problem is to communicate each other. I have established connection:
#OnClick(R.id.connectButton)
void onConnectButton() {
if (rxBleDevice == null) {
if (myViewModel.getMacAddress().getValue() != null) {
if (!myViewModel.getMacAddress().getValue().isEmpty()) {
// get BLE device
rxBleDevice = SampleApplication.getRxBleClient(this.getActivity())
.getBleDevice(myViewModel.getMacAddress().getValue());
// establish connection
connectionObservable = rxBleDevice.establishConnection(false)
.takeUntil(disconnectTriggerSubject);
// .compose(ReplayingShare.instance());
/*
reason: no instance(s) of type variable(s) T exist so that ReplayingShare<T> conforms to
ObservableTransformer<? super RxBleConnection, ? extends R
*/
statusTextView.setText(R.string.connected);
}
}
} else {
triggerDisconnect();
statusTextView.setText(R.string.disconnected);
}
}
and then I just use the connectionObservable to send data like this:
if (rxBleDevice != null) {
// if (isConnected()) {
final Disposable disposable = connectionObservable
.firstOrError()
.flatMap(rxBleConnection -> rxBleConnection.writeCharacteristic(uuid, HexString.hexToBytes(data)))
.subscribe(
bytes -> onWriteSuccess(bytes),
throwable -> onWriteFailure(throwable)
);
compositeDisposable.add(disposable);
// }
}
The error what I always got is:
Already connected to device with MAC address EA:A5:34:E6:28:2E, but if i try to isConnected() always says that they are not connected. Is there a way to send data every 300 ms to IoT device?
Full stack trace below.
I/VideoFragment: Write error:
com.polidea.rxandroidble2.exceptions.BleAlreadyConnectedException: Already connected to device with MAC address EA:A5:34:E6:28:2E
at com.polidea.rxandroidble2.internal.RxBleDeviceImpl$1.call(RxBleDeviceImpl.java:84)
at com.polidea.rxandroidble2.internal.RxBleDeviceImpl$1.call(RxBleDeviceImpl.java:72)
at io.reactivex.internal.operators.observable.ObservableDefer.subscribeActual(ObservableDefer.java:33)
at io.reactivex.Observable.subscribe(Observable.java:12284)
at io.reactivex.internal.operators.observable.ObservableTakeUntil.subscribeActual(ObservableTakeUntil.java:38)
at io.reactivex.Observable.subscribe(Observable.java:12284)
at io.reactivex.internal.operators.observable.ObservableElementAtSingle.subscribeActual(ObservableElementAtSingle.java:37)
at io.reactivex.Single.subscribe(Single.java:3666)
at io.reactivex.internal.operators.single.SingleFlatMap.subscribeActual(SingleFlatMap.java:36)
at io.reactivex.Single.subscribe(Single.java:3666)
at io.reactivex.Single.subscribe(Single.java:3652)
at com.example.automotive.Fragments.VideoFragment$1.onMove(VideoFragment.java:275)
at io.github.controlwear.virtual.joystick.android.JoystickView$2.run(JoystickView.java:860)
at android.os.Handler.handleCallback(Handler.java:914)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7560)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
isConnected method:
private boolean isConnected() {
return rxBleDevice.getConnectionState() == RxBleConnection.RxBleConnectionState.CONNECTED;
}
Is there a way to send data every 300 ms to IoT device?
Of course there is. If there is no external source of the data to send one could use code similar to:
bleDevice.establishConnection(false)
.flatMap(rxBleConnection ->
Observable.interval(300, TimeUnit.MILLISECONDS)
.flatMap(ignored -> rxBleConnection.writeCharacteristic(uuid, HexString.hexToBytes(data)))
)
.subscribe(
ignored -> {},
error -> { /* log or something */ }
);
The above assumes nothing else is subscribing to bleDevice.establishConnection(false) at the same time.
I think what you wanted to ask is why you get this exception and how to live with it. This exception was introduced to protect users from calling a stateful BLE transmission from multiple places in the code and messing it up. There is a wiki page about it.
You can share a Observable<RxBleConnection by using RxReplayingShare for instance. Then you will not get BleAlreadyConnectedException. You have tried that but apparently commented out the line because the compiler couldn't find out what is the type of object it will replay/share. Perhaps specifying it with ReplayingShare.<RxBleConnection>instance() would help?

Internet Connection Check behaving weirdly

I've been needing a way to check if the user has Internet. I used this approach:
public class InternetCheck extends AsyncTask<Void, Void, Boolean> {
private Consumer mConsumer;
public interface Consumer {
void accept(Boolean internet);
}
public InternetCheck(Consumer consumer) {
mConsumer = consumer;
execute();
}
#Override
protected Boolean doInBackground(Void... voids) {
try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
sock.close();
Log.w("INTERNET CHECK", "has Internet");
return true;
} catch (IOException e) {
Log.w("INTERNET CHECK", "NO Internet");
return false;
}
}
#Override
protected void onPostExecute(Boolean internet) {
mConsumer.accept(internet);
}
}
... the following way:
new InternetCheck(hasInternet -> { /* do something with boolean response */ });
However, it seems like it isn't as robust as one would think: sometimes (not so often) my phone is connected to WiFi and yet this method returns false.
What are the possible scenarios/diagnostics as of why this behaviour might happen?
My personal experience is that it seems to happen when my phone has my application open and is connected to a WiFi. Then, the phone goes to sleep and I move places and open it back up to the application on a new WiFi connection. The check returns false despite my phone displaying that it clearly has established the new WiFi connection (since it was a saved network).
However, this is not the only way this method seems to have failed. Another developer had it happen while he didn't change his WiFi connection.
Wifi connections are disconnected when the phone goes to sleep. It takes time for the connection to be re-established when the phone wakes up again.
Your 1.5 second connection timeout is too short to accommodate that extra delay.
Also, the DNS server, or the intermediate network, may simply be busy. Again, the connection timeout is too short.
Before inventing your own way to check internet connectivity, you should read these:
Android Developer Guide: Determine and monitor the connectivity status
StackOverflow: Android check internet connection

Android to BLE write fails when writing more than a few bytes in quick succession

I can successfully write to an RN4020 module from my Android device. An LED lights up on the module to indicate successful receipt of transmission and I can see the ASCII character transmitted to RN4020 on an Arduino terminal.
The problem is: when I try to send characters in quick succession (for example, each time when a button on my Android app is pressed very quickly) then after 5 to 10 successful transmissions:
RN4020 stops receiving: the LED to indicate Rx never turns on and I can't see transmitted characters on the terminal.
Most times Android device doesn't recognize that the write failed but sometimes I get the following error:
D/BluetoothGatt: writeCharacteristic: mDeviceBusy = true, and return false
My code to write to BLE (everytime a button is clicked I call sendDataToRN4020):
public boolean sendDataToRN4020(char instruction){
//check mBluetoothGatt is available
if (mBluetoothGatt == null) {
Log.e(TAG, "lost connection");
return false;
}
BluetoothGattService Service = mBluetoothGatt.getService(UUID.fromString("<address uuid>"));
if (Service == null) {
Log.e(TAG, "service not found!");
return false;
}
BluetoothGattCharacteristic charac = Service.getCharacteristic(UUID.fromString("<service uuid>"));
if (charac == null) {
Log.e(TAG, "char not found!");
return false;
}
byte[] value = new byte[1];
value[0] = (byte) (instruction);
charac.setValue(value);
boolean status = mBluetoothGatt.writeCharacteristic(charac);
return status;
}
This is my callback for writeCharacteristic:
#Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.i(TAG, "Successful transmission");
}
}
This may not be an Answer to your problem but I have not enough reputation to comment so I made an answer, I worked in an application using BLE to transfer data, I ran into a problem similar in which the app stops transmission even when the BLE device it's displaying that there's connection, this was because I had a scanner for compatible BLE devices, sometimes the app connects to a device multiple times because the app is constantly scanning for signals, don't know if you are doing something similar but I would recommend the following, before making a connection make sure that if there's a previous one, disconnect:
public static void connect(final String address, final String devicename, Context context) {
mContext = context;
if (mBluetoothAdapter != null && address != null) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device != null) {
forceDisconnect();
Log.i(TAG,"starting connection");
mBluetoothGatt = device.connectGatt(context, false, mGattCallback);
}
}
This is the method to disconnect:
public static void forceDisconnect(){
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect(); // from any connected device
if (mBluetoothGatt != null) mBluetoothGatt.close();
mBluetoothGatt = null;
}
I'm not sure if this is going to be of any help, what I can tell you is that after I did this adjustments to my code I was able to send data from the BLE device without issues, perhaps it's worth knowing how is your connection code to the BLE device, anyways hope it helps.
The problem was eventually resolved. The code in the question runs perfectly on a recently released Android device. The reason the failure was happening was that the device being used for testing at the time of posting this question was at least 3 years old. Newer devices have more robust support for BLE.

BLE Android - onConnectionStateChange not being called

I have a problem trying to connect to a peripheral. Sometimes the callback onConnectionStateChange(...) is not called after BluetoothDevice#connectGatt(...). What I'm trying to achieve is fast and short connections triggered by user action.
This situation occurs about 1 every 10 times without specific prior action. It lasts about 20 to 30 seconds or until the application is killed and reopened. The normal sequence of steps I follow is:
Scan devices to find the peripheral.
Call BluetoothDevice#connectGatt(...). If it takes longer than 1 second to connect, it means that the connection is "stuck" and therefore it won't connect, so BluetoothDevice#connectGatt(...) is called again. This is done with a limit of 5 attempts.
onConnectionStateChange(...) is called with newState CONNECTED and begins the services discovery.
The rest of the operations are performed without problems.
After disconnection BluetoothGatt#close() is called.
The problem occurs at point 3. Sometimes onConnectionStateChange(...)is not called. I have noticed that most of the times the problem starts with a specific behavior. After calling BluetoothDevice#connectGatt(...), onConnectionStateChange(...) is called with newState CONNECTED, but almost immediately afterwards (~40 milliseconds) is called again with newStatus DISCONNECTED. Due to the short time of the status change, I can deduce that the device does not even tried to make the connection and changed the state to DISCONNECTED.
The problem ends when:
20-30 seconds have passed. During this time onConnectionStateChange(...) is never called. When the problem ends, onConnectionStateChange(...) is called the number of times that the app tried to connect. For example, if BluetoothDevice#connectGatt(...) is called 15 times, onConnectionStateChange(...) is called 15 times with newState equal to DISCONNECTED. This is curious because never in any of those connection attempts the status changed to CONNECTED.
The app is killed and started again.
This error occurs in SDK18 and SDK 21.
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
String deviceName = device.getName();
if (deviceName == null) return;
Log.d("BLUETOOTH CONNECTION", "Device found: " + device.getName());
if (mMode == SCAN_MODE) {
mListener.deviceFound(device, rssi, scanRecord);
}
else {
mDevices.put(device.hashCode(), device);
stopScan();
// Samsung devices with SDK 18 or 19 requires that connectGatt is called in main thread.
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d("BLUETOOTH CONNECTION", "Executing first device.connectGatt()");
BluetoothGatt gatt = device.connectGatt(mContext, false, mGattCallback);
retryIfNecessary(device, gatt);
mTryingToConnect = true;
}
});
}
}
private void retryIfNecessary(final BluetoothDevice device, final BluetoothGatt gatt) {
if (isRetryLimitReached()) {
Log.d("BLUETOOTH CONNECTION", "Try count limit reached");
finishConnection(gatt);
mRetryCount = 0;
mListener.error(TIMEOUT);
return;
}
mRetryCount++;
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
Log.d("BLUETOOTH CONNECTION", "Check if it is frozen.");
if (isWorking()) {
Log.d("BLUETOOTH CONNECTION", "Frozen, create new connection.");
BluetoothGatt gatt = device.connectGatt(mContext, false, mGattCallback);
retryIfNecessary(device, gatt);
}
}
}, RETRY_INTERVAL_MS);
}
#Override
public void onConnectionStateChange(final BluetoothGatt gatt, int status, int newState) {
Log.d("BLUETOOTH CONNECTION", "On connection state changed. Device: "+ gatt.getDevice().getAddress());
if (!mConnected && BluetoothGatt.STATE_CONNECTED == newState) {
Log.d("BLUETOOTH CONNECTION", "Connected");
mTryingToConnect = false;
mTryingToDiscoverServices = true;
mConnected = true;
gatt.discoverServices();
}
else if(BluetoothGatt.STATE_DISCONNECTED == newState) {
Log.d("BLUETOOTH CONNECTION", "Disconnected and closing gatt.");
mConnected = false;
gatt.close();
if (!mConnectionFinished && mRetryCount == 0) {
finishConnection(gatt);
}
}
}
I think that the peripheral is not relevant, because the iOS app can always connect without this problem.
Any ideas? Thanks in advance.
Edit!
This answer say that:
Direct connection has interval of 60ms and window of 30ms so
connections complete much faster. Additionally there can only be one
direct connection request pending at a time and it times out after 30
seconds. onConnectionStateChange() gets called with state=2,
status=133 to indicate this timeout.
So in this 30 seconds interval there is a pending connection request and times out at the second 30. It's unlikely but, is there anything I can do to make this time shorter? Or maybe there is an explanation for the connection failure that I am not seeing. Thanks.
EDIT 02/03/2016
A new information that may help. When the problem starts (when onConnectionStateChange(...) is called with newState=DISCONNECTED after ~40ms of being called with newState=CONNECTED), the status is 62 = 0x03E. Looking here that status code means GATT_CONN_FAIL_ESTABLISH. When I detect this status I'm closing the gatt connection, but the problem persists. I also tried disconnecting and closing. Ideas? Thanks.
If someone is having a similar issue, the problem was finally solved by changing the BLE chip used by the peripheral (arduino). Before that change, a workaround I found was turning off and on the BLE after each connection. The solution was not perfect, but improved the connection rate a lot.
Android Bluetooth needs to be recycled occasionally, have you tried restarting the BLE on the device when you encounter this timeount?
Here's a snippet I've used to restart the BLE when strange things start happening.
static Handler mHandler = new Handler();
public static void restartBle() {
final BluetoothManager mgr = (BluetoothManager) ApplicationBase.getAppContext().getSystemService(Context.BLUETOOTH_SERVICE);
final BluetoothAdapter adp = mgr.getAdapter();
if (null != adp) {
if (adp.isEnabled()) {
adp.disable();
// TODO: display some kind of UI about restarting BLE
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (!adp.isEnabled()) {
adp.enable();
} else {
mHandler.postDelayed(this, 2500);
}
}
}, 2500);
}
}
}
I am not sure if you're still looking for an answer for this question. Personally, I would not advise making "fast and short connections triggered by user action" for low energy devices. Instead you could set the autoConnect option to "true" in your connectGatt method.
device.connectGatt(mContext, true, mGattCallback); [instead of false]
Hope it helps!

GCM after unregister still receive notifications

I am using GCM. Its work perfect but after unregister i still receive notifications.
This is my registration:
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(context);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(context);
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(context);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(context, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(context)) {
// Skips registration.
Toast.makeText(context, "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(context, user, pass, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}`
And from different activity i am trying to unregister from GCM:
GCMRegistrar.unregister(getApplicationContext());
GCMRegistrar.onDestroy(getApplicationContext());
And after that i still receive notifications :(
First, GCMRegistrar is deprecated.
Second, unregister() indicates that this device should never again receive messages. Frequently registering and unregistering is not expected app behavior. If you want to stop receiving messages, tell your app server to stop sending them.

Categories