How to retrieve provider time in Android programmatically? - android

I am doing an android app which has to display the current server/network operator time since the device time can be changed by the user. I don't want to change/set the device time. I tried few source codes but they didn't work well. I'm able to get device date and time but I need date and time from server or network provider itself. please help me

It seems that you need to interface with the Network Time Protocol (NTP).
There are similar questions here on SO use of ntp service, get datetime from network provider (as noted by Gheo) suggesting to:
use android.net.SntpClient.java source code and javadocs
read through this Google Groups thread
As noted in the comments of these posts, as of Honeycomb you cannot do any network operations in the main activity thread (suggestion: use a service instead).
Update:
A further search led me to find Dominik Schürmann's ntp-sync repository on GitHub. He provides different examples of how you can use his library which you can compile and run on your emulator/device.

I had found a solution but forgot to post it. In case somebody finds it helpful, here is what worked for me.
Get the server time using an API or network call wherein the response will have the timestamp from the server. Use the data as per your convenience.
You can modify the existing API itself, if any.

Related

Android BLE BluetoothGatt.writeDescriptor() return sometimes false

I'm trying to write BLE Android app. I found that sometimes when I call
BluetoothGatt.writeDescriptor() it returns false.
I have not found in documentation any note of limitation to this function. But ppl on stack overflow says that I need to wait for BluetoothGattCallback.onDescriptorWrite() before I try to write another descriptor.
Here is one reply saying that BLE is busy with writeDescriptor() and can not do other write.
Here is another thread saying that you can not call twice writeCharacteristic().
My questions are
is it really true?
is there really missing some internal android API buffer for serializing BLE requests and every developer has to do it on it's own?
Is it true for different functions? For example when I call writeDescriptor() I understand I can not call second time writeDescriptor() before I receive onDescriptorWrite(). But do I have to wait for onDescriptorWrite() when I want to call writeCharacteristic()?
Also if there is inter-function dependency then what else function have this limitation (namely: readCharacteristic(), readDescriptor(), requestMtu()...)?
And additionally is there interdependency between BluetoothGattServer and BluetoothGatt. So for example when I call BluetoothGattServer.notifyCharacteristicChanged() shall I wait forBluetoothGattServerCallback.onNotificationSent before I can call BluetoothGatt.writeDescriptor() or BluetoothGatt.writeCharacteristic()? (BTW praise for google documentation onNotificationSent() is by luck documented properly. Doc says:
When multiple notifications are to be sent, an application must wait
for this callback to be received before sending additional
notifications.
Lastly having all this questions - I feel that Android BLE API is under-documented. Or am I wrong and there is documented somewhere what are allowed methods calling sequences? If yes can you please point me to such documentation? If not is there some channel we can open issue with google and ask them to add to documentation something? I mean it may not be much text - some function like onNotificationSent() is arleady properly documented. They just need to copy this sentence to other functions.
The documentation lacks information. However you can read the source code to find out the rules, which (currently) are the following:
For each BluetoothGatt object, you can only have one outstanding request at a time, including requestMtu, readCharacteristic, writeCharacteristic, readDescriptor, writeDescriptor and executeReliableWrite. So if you issue a read request you need to wait for the read response before you issue a write request. While they implemented the code that returns false if there is an ongoing operation in BluetoothGatt.java, they forgot to do this for requestMtu, so if you have multiple requests at a time where requestMtu is one of them, you will get random errors sooner or later (in the latest versions at the time of this post).
So yes, every developer has to manually serialize the requests. Note that the Bluetooth stack actually has a queue of requests, but it is limited to only one request per client (i.e. BluetoothGatt object). So if two apps on the same phone talk to the same device simultaneously you will never get "busy" errors. The only exception is if you use Write Without Response for which the current data flow implementation is quite buggy (see https://issuetracker.google.com/issues/37121017 which Google seems to have ignored).
You can send notifications at the same time as you write a characteristic, since the server and client roles are separated.
Regarding updating the documentation, you can always try to file an issue at https://issuetracker.google.com (but I get the feeling nobody reads that), or, since Android is open source, send a pull request to https://android-review.googlesource.com/ which updates the Javadoc from which the documentation is generated.

change string values in firebase database even when app is closed

I'm kind of confused about how to do this. I have string values in the realtime database in firebase console. They change when the app is running because the code is causing the values to change, but when the application is stopped, the values won't change anymore. I want the values to change even when the application is running or not. So for example, a counter variable in the database will go up every minute forever as long as the data is there.
From your explanation this seems to be an issue which can be easily solved by keeping the app running in background. For this purpose look here.
Quoting the answer from above link
A very simple answer for your problem is to use Service. It will allow you to perform variety of tasks while being in background and is your best bet for sending your location to server silently.
Read this answer for help.
Although both the answers are related to location update but they can be easily extended to fulfill your requirements.
Hint: The above quoted answers are sending the data to a server at frequent intervals. Send your data to Firebase server when the data-field is changed.
Hope this answers your query. Provide some code I might help with that too, if I get time.

Asynchronous requests to server posted in a loop - Android

I am a Java developer with no Android experience, and I am trying to quickly put an app together. It seems that what I would normally do in Java isn't helping.
At this stage, ease of implementation is more important than efficiency or style - I will sort the latter out when there is more time and I will have educated myself properly when it comes to Android.
People can use the app to ask for support, or offer it to those who need it. Asking for support posts a request with the details to the server, and that's done.
Now I would like the app to post an asynchronous request to the server, to be notified of outstanding support requests once a minute. I guess it's the same principle of WhatsApp checking if there is any new message on the server.
I tried doing that in a separate thread with an infinite loop which sleeps for 60 seconds but for some reasons that stops the UI from working.
From what I now understand, I should use a service with a Looper, a Timer and a Handler. Is that correct?
Could anybody point me to a tutorial which explains exactly what to do, step by step? Or at least suggest keywords I should look for?
All I found so far are snippets of code which don't work together when I try to assemble it. Possibly because I am not searching for the right terms?
Thanks, Dan
You could try the following approach:
Create a service that runs in the background to check for newly added data in the server.
If you prefer to make it user-driven, you can let users refresh the list on the device to actually trigger the requests to the server.
Libraries like Retrofit can make your life easier when it comes to making http requests - always avoid the main UI thread when doing this.
Another library that you could use to decouple your application using Events is EventBus. Assuming you are running a background service to check for updates, you can use EventBus to update your User Interfaces when something new is retrieved from the server through a GET request.
I hope this gives you an idea on how to proceed with the solution. Good luck!

SyncAdapter alternatives

I think its well known that in list of worst-documented topics, SyncAdapter shines bright like a diamond !
acording to http://udinic.wordpress.com/2013/07/24/write-your-own-android-sync-adapter/ SyncAdapter brings 4 main benefits :
A) Battery efficiency
B) Interface C) Content awareness D) Retry mechanism;
if in any case there's a need to sync an sqlite DB with remote SQL DB, and none of these benefits is needed, what other alternatives are there**?** its easy to manage a service in-between the DBs with php, I did that for Uploading part of syncing process,but for the downloading part I feel silly if I use the query filling method,cause in near future remote db might get large and larger.the only solution that comes to my mind is to write my own sync activity/service, but I dont know how to access the last update date to SQLite db/table (other than specifying a _date in every table,) to check if it is necessary to sync again ? I feel my head is between two places!
You are mixing the problem.
1- Do you really have to use sync Adapter ??? So if yes, you are gonna have a Sync call per table and no needs to save the last call date. Android will do it for you. Just setup your sync timers properly
2- other solution is to do a simple AsyncTask and do your job here. (For exemple if you have to do it only once per week)
For your date problem, the thing is if you really wants to know if you are up to date you got many solutions. On your server save the date, or increment a version and compare these when you call a sync from your device to know if you have to sync or not.
An other solution is to simply just refresh your db wherever it is updated or not(for exemple you got a small db, so no need to create an optimized system).
I faced the same problem months ago and hoped this helped you.
You might want to consider this article:
https://www.bignerdranch.com/blog/choosing-the-right-background-scheduler-in-android/
It makes it clear how syncadapter is a good choice as a result of lesser convenient options when needing to utilize the battery well and go out to the network.
I don't recommend Asyntask for theses reasons:
http://blog.danlew.net/2014/06/21/the-hidden-pitfalls-of-asynctask/
If syncadapter is really not working for you there is
android's best practices which suggests to use an IntentService and WakefulBroadcastReceiver with partial wake lock when doing long-running operations. It says "the Android framework offers several classes that help you off-load operations onto a separate thread that runs in the background. The most useful of these is IntentService."
https://developer.android.com/training/run-background-service/index.html
https://developer.android.com/training/scheduling/wakelock.html
there must be some truth to it since they wrote it.
Android Jetpack includes WorkManager which is a valid alternative to syncadapters.
Main features:
Schedule a job according to network availablity or device charging status
Backward compatiblity up to api 14
Ensures task execution, even if the app or device restarts
Intended for deferrable tasks (E.g periodically syncing application data with a server)
In alternative, something similar is Android-Job library by Evernote

Scheduling a weekly task for an Android app

In the app that I'm developing, I want to have re-occuring task on each Monday (possibly at 00.01 AM).
The task is basicly as follows:
I will connect to a web service, to check whether there is a parameter or a new file to be fetched in order to use with the app itself.
Also, I need to send some data, which is basicly some data evaluated on that week, and restart the process on an on again.
After a ton of reading and so on, I think it may be more appropiate to use an AlarmManager implementation, since I do not see any need for using the UI etc (but I am open to suggestions, of course)
Probably the main question is that how can I easily schedule a task that when we are on the next week's Monday, at 00.01 AM or whatever, the system will check for Internet connection and if possible connect with that web services to send & retrieve data? The app is not supposed to be open I guess, but please note that the stored data is basic key value pairs in a preference file on that app.
The best approach for your case would be to use the AlarmManager. More info you can find here: http://developer.android.com/reference/android/app/AlarmManager.html
A small example is here: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/AlarmService.html
And here for a more extended example: Android: How to use AlarmManager
Hope this helps!!

Categories

Resources