is there any way to change an android device time from a cordova app?
I need to sync the device time with a server.
The app gets the server time from a webapi and if it's different from the device time i'd like to change the device time.
Thanks
You should not try to bend the whole device just to make your app work. What if the server-time is wrong? What if the user wants a different time?
We have the same needs for our app, and what we are doing is to run the app in server-time.
This is native Android in Java, but I think the idea should be clear and should also be possible in Cordova.
So we have this ServerTime class, and whenever we need the current time in our app, we do not use new Date() or System.currentTimeMillis(), but instead use ServerTime.now().
The class looks something like this (written from memory and simplified, make sure to test, maybe the diff-calculations should be + instead of - ...):
public static class ServerTime {
private static long diffMillis;
public static Date now() {
long millis = System.currentTimeMillis() - diffMillis;
return new Date(millis;
}
public static void update(long serverTimeMillis) {
diffMillis = System.currentTimeMillis() - serverTimeMillis;
}
}
The server provides the server's time with every response and additionally we poll the server-time every 15 minutes or so. Whenever we get the server's time, we call ServerTime.update(server's time in millis).
Related
I have an app that should show a notification every 2 hours and should stop if user has already acted upon the notif. Since background services are history now, I thought of using WorkManager ("android.arch.work:work-runtime:1.0.0-beta01") for the same.
My problem is that although the work manager is successfully showing the notifications when app is running, but it won't show notification consistently in the following cases(I reduced the time span from 2 hours to 2 minutes to check the consistency):
when app is killed from the background.
device is in screen off.
state device is in unplugged state(i.e not charging).
By consistency , i mean that the notifications show at least once in the given time span. for 2 minutes time span, the freq of notifications went from once every 4 minutes to completely not show any notification at all. for 2 hours timespan( the timespan that i actually want), its been 4 hours and i haven't got a single notification. Here is the Code i am using for calling WorkManger:
public class CurrentStreakActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
setDailyNotifier();
...
}
private void setDailyNotifier() {
Constraints.Builder constraintsBuilder = new Constraints.Builder();
constraintsBuilder.setRequiresBatteryNotLow(false);
constraintsBuilder.setRequiredNetworkType(NetworkType.NOT_REQUIRED);
constraintsBuilder.setRequiresCharging(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
constraintsBuilder.setRequiresDeviceIdle(false);
}
Constraints constraints =constraintsBuilder.build();
PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest
.Builder(PeriodicNotifyWorker.class, 2, TimeUnit.HOURS);
builder.setConstraints(constraints);
WorkRequest request = builder.build();
WorkManager.getInstance().enqueue(request);
}
....
}
Here is the worker class(i can post showNotif(..) and setNotificationChannel(...) too if they might be erroronous):
public class PeriodicNotifyWorker extends Worker {
private static final String TAG = "PeriodicNotifyWorker";
public PeriodicNotifyWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
Log.e(TAG, "PeriodicNotifyWorker: constructor called" );
}
#NonNull
#Override
public Result doWork() {
// Log.e(TAG, "doWork: called" );
SharedPreferences sp =
getApplicationContext().getSharedPreferences(Statics.SP_FILENAME, Context.MODE_PRIVATE);
String lastcheckin = sp.getString(Statics.LAST_CHECKIN_DATE_str, Statics.getToday());
// Log.e(TAG, "doWork: checking shared preferences for last checkin:"+lastcheckin );
if (Statics.compareDateStrings(lastcheckin, Statics.getToday()) == -1) {
Log.e(TAG, "doWork: last checkin is smaller than today's date, so calling creating notification" );
return createNotificationWithButtons(sp);
}
else {
Log.e(TAG, "doWork: last checkin is bigger than today's date, so no need for notif" );
return Result.success();
}
}
private Result createNotificationWithButtons(SharedPreferences sp) {
NotificationManager manager =
(NotificationManager) getApplicationContext().getSystemService((NOTIFICATION_SERVICE));
String channel_ID = "100DaysOfCode_ID";
if (manager != null) {
setNotificationChannel(manager,channel_ID);
showNotif(manager, channel_ID, sp);
return Result.success();
}
else {
return Result.failure();
}
I am using a xiaomi miA2 androidOne device with Android Pie(SDK 28). There are a few other things that are troubling me:
What can i possibly do to know if my WorkManager is running? Other that just wait for 2 hours and hope for a notification. I actually tried something like that, keeping my phone connected to pc and checking android studio's logcat every now and then. It DOES run all the logs when the worker is actually called, but i don't think that's a correct way to test it, or is it?
In the above Code, the setDailyNotifier() is called from the onCreate() every time the app is opened. Isn't it Wrong? shouldn't there be some unique id for every WorkRequest and a check function like WorkManger.isRequestRunning(request.getID) which could let us check if a worker is already on the given task??If this was a case of AsyncTask, then boy we would have a mess.
I have also checked #commonsware's answer here about wakelock when screen is off, but i remember that work manager does use alarm manager in the inside when available. So what am I missing here?
Few comments:
WorkManager has a minimum periodic interval of 15minutes and does not guarantee to execute your task at a precise time. You can read more about this on this blog.
All the usual background limitation you've on newer Android releases are still relevant when you use WorkManager to schedule your tasks. WorkManager guarantees that the task are executed even if the app is killed or the device is restated, but it cannot guarantee the exact execution.
There's one note about the tasks being rescheduled when your app is killed. Some OEM have done modification to the OS and the Launcher app that prevents WorkManager to be able to accomplish these functionality.
Here's the issuetracker discussion:
Yes, it's true even when the phone is a Chinese phone.
The only issue that we have come across is the case where some Chinese OEMs treat swipe to dismiss from Recents as a force stop. When that happens, WorkManager will reschedule all pending jobs, next time the app starts up. Given that this is a CDD violation, there is not much more that WorkManager can do given its a client library.
To add to this, if a device manufacturer has decided to modify stock Android to force-stop the app, WorkManager will stop working (as will JobScheduler, alarms, broadcast receivers, etc.). There is no way to work around this. Some device manufacturers do this, unfortunately, so in those cases WorkManager will stop working until the next time the app is launched.
As of now , i have this app installed for last 8 days and i can confirm that the code is correct and app is working fine. as said by pfmaggi , the minimum time interval for work manager to schedule the work is 15 minutes, so there is a less chance that the WorkManager would have worked as expected in my testing conditions( of 2 minutes ) . Here are some of my other observations:
Like I said in the question that i was unable to recieve a notification for 4 hours even though i have passed the repeat interval as 2 hours. This was because of Flex Time. I passed in the flex time of 15 minutes and now it shows notifications between correct time interval. so i will be marking pfmaggi's answer as correct.
The problem of repeated work request can be solved by replacing WorkManager.getInstance().enqueue(request) with WorkManager.getInstance().enqueueUniqueWork(request,..)
I was still unable to find a way to test the work manager in the way i have described.
We want to add a reporting feature to our existing application.
For this purpose we are sending Events in JSON via HTTPS to a server application.
We need to remember Event-objects that could not be send to the server (No internet, server not reachable...). We are considering to store the events in a SQLite database and discard all Events that are older than 24 hours to prevent flooding our storage.
Another option would be to write the JSON-objects to a file and concat each new event when it could not be send to the server. The problem with this solution is, that it would be hard for us to discard logs older than 24 hours.
We store the event sin a table with the columns:
| id | json | created_at |
Can anyone recommend best practices for this use case?
Currently we tend to use the sqlite solution but we are wondering if there are any caveats that we are not aware of.
If you don't mind using third-party lib i can recommend android-priority-jobqueue. You can easily achieve what you are trying to do. You can always create job and it will handle itself. You can set if it needs network, if it is persistent (saved into DB when no network) and even you can customize your own retry logic.
Here's little example.
public class PostTweetJob extends Job {
public static final int PRIORITY = 1;
private String text;
public PostTweetJob(String text) {
// This job requires network connectivity,
// and should be persisted in case the application exits before job is completed.
super(new Params(PRIORITY).requireNetwork().persist());
}
#Override
public void onAdded() {
// Job has been saved to disk.
// This is a good place to dispatch a UI event to indicate the job will eventually run.
}
#Override
public void onRun() throws Throwable {
// yours code here
}
#Override
protected RetryConstraint shouldReRunOnThrowable(Throwable throwable, int runCount,
int maxRunCount) {
// An error occurred in onRun.
return RetryConstraint.createExponentialBackoff(runCount, 1000);
}
}
And you call it like this.
jobManager.addJobInBackground(new PostTweetJob("It works"));
use JobService(Android 5+ - lollipop and above) and AlarmManager (for android sdk<21 - pre lollipop) with this solution u can schedule any task and it would be performed. JobService was developed rxactely for tjis purposes(schedule and perform different tasks) maybe you can try JobIntentService it is would work on kitkat(android 4+) devices
P.S.
In that case you didnt need any third party libs and other dependrncies like firebase/google play services(like for FirebaseDispatcher)
I am using History API of Google Fit to get the step count into my app. I have run a service and the step count is updated after a regular interval. When my app is in foreground, it works fine and I get the step count but when my app goes background, services works fine and Fitness.HistoryApi.readData does not fetch the steps. I require the steps count even when the app is in background or even when the app is killed.
Here is my problem code snippet:
private class InsertAndVerifyDataTask extends AsyncTask<String,String,String> {
protected String doInBackground(String...params) {
readRequest = queryFitnessData();
dataReadResult =
Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES);
if(dataReadResult!=null) {
printData(dataReadResult);
}
return "s";
}
protected void onPostExecute(String result){
if(result.equals("s")) {
compareData();
}
}
}
And on debug the method Fitness.HistoryApi.readData gives status as TIME_OUT when app is in background or killed.
Please help me out, I am just a beginner in Android.
You might want to use the Fitness.RecordingApi to keep recording your steps even when the app is killed.
If you are using the SensorsApi to get the step count, it wont work when your app is killed. RecordingApi is like telling the SDK- "Hey!, keep recording the steps for me even when I'm gone". And when the user comes back to your app, you can fetch the data using the getDailyTotal or readData.
See reference here
Warning: however,RecordingApi takes some time for update- you dont know at what time interval the data is updated- which means user might not be seeing the updated data. See here.
I'm trying to implement a convenient-to-use system for handling status bar notifications for android, and i was thinking about the following:
Create a database, where i store when and what to show
Create a service what runs in the background using the 'interval' Service, what the API provides
In that service check if any notification needs to be shown according to the database, then show it.
The only problem is, that, i cannot detect, if i need to start the service or not. I tried these things, but none of them worked well so far:
1.) Save if the service was already started on the local storage:
// Do this on application startup
var isRunning = Ti.App.Properties.getBool("service_running", false);
if(!isRunning)
{
var service = Titanium.Android.createService(...);
service.addEventListener('start', function()
{
Ti.App.Properties.setBool("service_running", true);
});
service.addEventListener('stop', function()
{
Ti.App.Properties.setBool("service_running", false);
});
service.start();
}
This obviously won't work, because the android systems native onStop and onDestroy events will not be dispatched, if the Service doesn't terminates unusually (like the user force stops the app), so the stop event also won't be fired.
2.) Try to access any active service via Titanium.Android.getCurrentService(), but i got an error saying Titanium.Android has no method called getCurrentService(). This is pretty strange, because the IDEs code completion offered me this method.
3.) Use an Intent to clear the previously running Service
var intent = Titanium.Android.createServiceIntent
(
{
url : 'notification/NotificationService.js'
}
);
intent.putExtra('interval', 1000 * 60);
//Stop if needed
Titanium.Android.stopService(intent);
//Then start it
Titanium.Android.startService(intent);
But it seems like i need to have the same instance of Intent, that started the service to stop it, because doing this on application startup, then exiting and restaring it results in multiple Services to run.
At this point i ran out of ideas, on how to check for running services. Please if you know about any way to do this, let me know! Thanks for any hints!
EDIT
Here are the source materials which gave me the idea to try the above methods (maybe only i use them incorrectly):
The local storage: Titanium.App.Properties
The method for accessing running services: Titanium.Android.getCurrentService
The method for stoping a service with an Intent: Titanium.Android.stopService
And the full source for the NotificationHandler "class" and NotificationService.js that I wrote, and their usage: link
Use Bencoding AlarmManager and it will provide all you need to schedule an alarm notification : https://github.com/benbahrenburg/benCoding.AlarmManager
This module provides what you need. It's really easy - just set repeat to daily when sheduling a Notification or Service.
Refer https://gist.github.com/itsamiths/6248106 for fully functional code
I am checking if the service is started then show daily notification or else start service and then show daily notification
var isRunning = Ti.App.Properties.getBool("service_running", false);//get service running bool status
if (isRunning) {
Ti.API.info('service is running');
} else {
Ti.API.info('service is not running');
alarmManager.addAlarmService({
service : 'com.mkamithkumar.whatstoday.DailyEventNotificatoinService',
hour : "08",
repeat : 'daily'
});
}
I come one year late, but maybe this can help others in the future.
We had the same idea: run the service forever and do the checks on every cycle (I must check 20 different communications).
And I had the same problem: how to detect that the service is running, to don't run again to don't duplicate the checks.
To solve that problem, what I did is get the current time on every cycle and save it to store.
Then, before launch a new service, I check if the last execution was to far in time: if true, then the service was stopped, else is running.
Not very elegant, but was the only way I found to avoid the problem of the user killing the app (and the service).
This is my code for the "launcher" of the service. In my case, I test 30 seconds far away:
exports.createAndroidServiceForNotifications = function(seconds) {
var moment = require('alloy/moment');
var diffSeconds = moment().diff(Ti.App.Properties.getString('serviceLastRun', new Date().getTime() - 60000), 'second');
if (diffSeconds > 30) {
var now = new Date().getTime();
var delta = new Date(now + (seconds * 1000));
var deltaMS = delta - now;
var intent = Ti.Android.createServiceIntent({
url : 'notificationsService.js'
});
intent.putExtra('interval', deltaMS);
Ti.Android.startService(intent);
}
};
I'm writing an app which should shows on the screen if user wasn't interract with phone for some time. (I'm going to write a service which will show an activity after this time)
EDIT: Activity may not be open (that's why I must define non-interaction time in service)
Yes, there's this awesome method onUserInteraction() in the Activity class.
You can store the current time as a long in a variable and display the time difference.
onUserInteraction(){
latestInteractedTime = System.currentTimeMillis();
}
// In some method you want to probably display the time difference
String diff = "Time diff: " + (System.currentTimeMillis() - latestInteractedTime);
textView.setText(diff);