I'm using UsageStatsManager API to get usage statistics for a certain time interval. All works fine if I use the predefined intervals i.e. INTERVAL_DAILY, INTERVAL_WEEKLY, INTERVAL_MONTHLY, INTERVAL_YEARLY. But if I want to view the data for the past 2 or 3 hours, I am getting today's data for the whole day. I have tried using Calendars and System.currentTimeMillis() but that didn't give me filtered results.
Calendar approach :
Calendar startCalendar = Calendar.getInstance();
startCalendar.add(Calendar.HOUR_OF_DAY, -2);
Calendar endCalendar = Calendar.getInstance();
And pass this to queryUsageStats method like this:
usageList = usm.queryUsageStats(interval, startCalendar.getTimeInMillis(), endCalendar.getTimeInMillis());
where interval is INTERVAL_BEST.
System.currentTimeMillis() approach :
long startTime = System.currentTimeMillis() - 7200*1000 // 7200 seconds i.e. 2 hrs
long endTime = System.currentTimeMillis();
Pass this to queryUsageStats just like above :
usageList = usm.queryUsageStats(interval, startTime, endTime);
where interval is again INTERVAL_BEST.
I'd like to know whether it's possible to get data for this duration i.e. less than a day, as the INTERVAL_BEST hasn't been documented properly to include this information. Any help would be appreciated as I'm stuck on this problem.
As UsageStatsManager doc says:
A request for data in the middle of a time interval will include that interval.
It seems that usage data is stored in buckets, and minimum bucket is a day, so you can't query usage stats for period less than a day. Even if you query a one-hour interval for a particular day, usage stats for the whole day is returned.
A little late to the party, but I think this might be useful to some.
You could use the queryEvents(long startTime, long endTime) from UsageStatsManager for achieving the desired result. The method could look like this (inspired by this post):
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public HashMap<String, AppUsageInfo> queryUsageStatistics(Context context, long startTime, long endTime) {
UsageEvents.Event currentEvent;
List<UsageEvents.Event> allEvents = new ArrayList<>();
HashMap<String, AppUsageInfo> map = new HashMap<>();
UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
assert mUsageStatsManager != null;
// Here we query the events from startTime till endTime.
UsageEvents usageEvents = mUsageStatsManager.queryEvents(startTime, endTime);
// go over all events.
while (usageEvents.hasNextEvent()) {
currentEvent = new UsageEvents.Event();
usageEvents.getNextEvent(currentEvent);
String packageName = currentEvent.getPackageName();
if (currentEvent.getEventType() == UsageEvents.Event.ACTIVITY_RESUMED || currentEvent.getEventType() == UsageEvents.Event.ACTIVITY_PAUSED ||
currentEvent.getEventType() == UsageEvents.Event.ACTIVITY_STOPPED) {
allEvents.add(currentEvent); // an extra event is found, add to all events list.
// taking it into a collection to access by package name
if (!map.containsKey(packageName)) {
map.put(packageName, new AppUsageInfo());
}
}
}
// iterate through all events.
for (int i = 0; i < allEvents.size() - 1; i++) {
UsageEvents.Event event0 = allEvents.get(i);
UsageEvents.Event event1 = allEvents.get(i + 1);
//for launchCount of apps in time range
if (!event0.getPackageName().equals(event1.getPackageName()) && event1.getEventType() == UsageEvents.Event.ACTIVITY_RESUMED) {
// if true, E1 (launch event of an app) app launched
Objects.requireNonNull(map.get(event1.getPackageName())).launchCount++;
}
//for UsageTime of apps in time range
if (event0.getEventType() == UsageEvents.Event.ACTIVITY_RESUMED &&
(event1.getEventType() == UsageEvents.Event.ACTIVITY_PAUSED || event1.getEventType() == UsageEvents.Event.ACTIVITY_STOPPED)
&& event0.getPackageName().equals(event1.getPackageName())) {
long diff = event1.getTimeStamp() - event0.getTimeStamp();
Objects.requireNonNull(map.get(event0.getPackageName())).timeInForeground += diff;
}
}
// and return the map.
return map;
}
The AppUsageInfo class would be:
public class AppUsageInfo {
public long timeInForeground;
public int launchCount;
AppUsageInfo() {
this.timeInForeground = 0;
this.launchCount = 0;
}
}
To then get the usage stats for the last two hours, simply call
Calendar startCalendar = Calendar.getInstance();
startCalendar.add(Calendar.HOUR_OF_DAY, -2);
Calendar endCalendar = Calendar.getInstance();
HashMap<String, AppUsageInfo> result = queryUsageStatistics(context, startCalendar.getTimeInMillis(), endCalendar.getTimeInMillis();
Related
I have the following code:
Calendar nextSchedule = Calendar.getInstance();
nextSchedule.set(Calendar.HOUR_OF_DAY, 0);
nextSchedule.set(Calendar.MINUTE, 0);
nextSchedule.set(Calendar.SECOND, 10);
nextSchedule.set(Calendar.MILLISECOND, 0);
nextSchedule.add(Calendar.DAY_OF_YEAR, 1);
Calendar cal = Calendar.getInstance();
long diff = nextSchedule.getTimeInMillis() - cal.getTimeInMillis();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
As expected, around 11am it gave me 13/12hours but when doing the following in a widget:
Calendar nextSchedule = Calendar.getInstance();
nextSchedule.set(Calendar.HOUR_OF_DAY, 0);
nextSchedule.set(Calendar.MINUTE, 0);
nextSchedule.set(Calendar.SECOND, 10);
nextSchedule.set(Calendar.MILLISECOND, 0);
nextSchedule.add(Calendar.DAY_OF_YEAR, 1);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextSchedule.getTimeInMillis(), pendingIntent);
Around 1:30am, it was still not updated. Only somewhen between 2am and 9am (I was asleep) it got updated.
A similar strange thing happens elsewhere. I have a calendar view (applandeo) with the following code: cvCalendar.setOnDayClickListener(eventDay -> showDateItems(eventDay,lvCalendar));
private void showDateItems(EventDay eventDay, ListView lvCalendar) {
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal.set(eventDay.getCalendar().get(Calendar.YEAR),eventDay.getCalendar().get(Calendar.MONTH),eventDay.getCalendar().get(Calendar.DATE));
cal2.set(eventDay.getCalendar().get(Calendar.YEAR),eventDay.getCalendar().get(Calendar.MONTH),1);
cal2.add(Calendar.MONTH, -1);
ArrayList<String> items = new ArrayList<>();
String line;
for (ItemsHistoryItem item: Utils.getInstance().itemsHistory) {
if (item.getxDay() < Utils.getInstance().calenderToEpoch(cal2) && item.getyDay() < Utils.getInstance().calenderToEpoch(cal2)) break;
if (item.getxDay() != Utils.getInstance().calenderToEpoch(cal) && item.getyDay() != Utils.getInstance().calenderToEpoch(cal)) continue;
line = item.getItemId() + ": $" + item.getAmount();
if (item.getxDay() == Utils.getInstance().calenderToEpoch(cal))
line += " (x day)";
else
line += " (y day)";
items.add(line);
}
ArrayAdapter<String> lcAdapter = new ArrayAdapter<>(requireActivity(), android.R.layout.simple_list_item_1, items);
lvCalendar.setAdapter(lcAdapter);
}
long calenderToEpoch(Calendar cal2) {
return TimeUnit.MILLISECONDS.toDays(cal2.getTimeInMillis());
}
Basically, the above code scans dates of items and when the user select a certain date, he gets a list of items which dates (x and y) are of that date. When doing so during the day, it works. When doing so in 1:30am (for example), it shifts one day ahead so if the user clicks on 12-oct, he gets the items of 11-oct. Somwhen between 2am and 9am it "shifts" back and works as expected.
Any idea what's wrong here?
I have a suggestion for using alarmmanager properly if you want it to fire exactly at the time you want else it does not fire on time when device is in deep sleep mode and gets delayed:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// use setAlarmClock function of AlarmManager
// but this function will show an alarm icon on statusbar
// if you dont want to show that icon you can use
// setExactAndAllowWhileIdle function but that will not be
// perfectly exact
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// use setExact function of AlarmManager
}
else {
// use set function of AlarmManager
}
Apparently the default timezone for Calendar.getInstance() in my case was GMT+3 so at 3am the items were shown for their dates and the widget was updated. to fix it, I simply did the following:
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
Is there Any service to check if the current time is night considering the winter and summer time changes ?
For example, the night in summer starts after 19:45 (in my local time), but in winter, night starts after 16:45.
My trial was:
Boolean isNight;
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
isNight = hour < 6 || hour > 18;
This code works only if if the night starts after 18:00, but night time changes according to the time in year.
You can use this sunrisesunset-lib and with a method like this and
your location you are able to find out it's night or not :
private boolean isNight(Location location) {
SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, TimeZone.getTimeZone("GMT+3:30"));
Calendar now = Calendar.getInstance();
Calendar officialSunrise = calculator.getOfficialSunriseCalendarForDate(now);
Calendar officialSunset = calculator.getOfficialSunsetCalendarForDate(now);
return !(now.after(officialSunrise) && now.before(officialSunset));
}
one more code is working for me
String time1 = "01:00:00";
String time2 = "15:00:00";
LocalTime time = LocalTime.parse(time2);
if ((time.isAfter(LocalTime.of(20,11,13))) || (time.isBefore(LocalTime.of(14,49,0))))
{
System.out.println("true");
}
else
{
System.out.println("false");
}
I'm using the NetworkStatsManager class to retrieve the data usage of the apps.
If I provide 01.01.2018 as start time, it shows that my phone has sent out 5,4 GB.
If I provide 01.01.2017, it still shows 5,4 GB.
This lets me assume that there is a limit somehow regarding the start time. The documentation unfortunately does not mention anything regarding this.
So, how much in time can we go back?
Code:
This is the code which retrieves the data using querySummary:
private long[] getBytesSummary(Context context, int networkType, Calendar calendar) {
NetworkStatsManager networkStatsManager = (NetworkStatsManager) context.getSystemService(Context.NETWORK_STATS_SERVICE);
NetworkStats networkStats = null;
try {
networkStats = networkStatsManager.querySummary(
networkType,
Util.getSubscriberId(context, networkType),
calendar.getTimeInMillis(),
System.currentTimeMillis());
} catch (RemoteException e) {
if (debug) Log.e(TAG, "getBytesSummary: " + e.toString());
}
long[] result = new long[2];
long totalRxBytes = 0;
long totalTxBytes = 0;
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
if (networkStats != null) {
while (networkStats.hasNextBucket()) {
networkStats.getNextBucket(bucket);
int uid = bucket.getUid();
long uidRxBytes = bucket.getRxBytes();
long uidTxBytes = bucket.getTxBytes();
if (uidsWithNetworkUsageMap.indexOfKey(uid) < 0) {
long[] uidBytes = new long[2];
uidBytes[0] = uidRxBytes;
uidBytes[1] = uidTxBytes;
uidsWithNetworkUsageMap.put(uid, uidBytes);
} else {
long[] value = uidsWithNetworkUsageMap.get(uid);
value[0] = value[0] + uidRxBytes;
value[1] = value[1] + uidTxBytes;
uidsWithNetworkUsageMap.put(uid, value);
}
totalRxBytes += bucket.getRxBytes();
totalTxBytes += bucket.getTxBytes();
}
networkStats.close();
}
result[0] = totalRxBytes;
result[1] = totalTxBytes;
return result;
}
As you can see above, I give a calendar object to the method.
This is how I get the calendar for the current year:
public static Calendar getCalendarCurrentYear() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, 1);
// for 0-12 clocks
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
// for 0-24 clocks
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
// calendar.set(Calendar.YEAR, 2017);
Log.i("DataUsage", "getCalendarCurrentYear: " + calendar.getTime());
return calendar;
}
This returns Mon Jan 01 00:00:00 GMT+01:00 2018.
If I set it now to 2017, the result is the same as for 2018.
Am I doing something wrong?
EDIT:
I just did some testing, the limit seems to be 3 months somehow.
Anything greater than 3 months as start time results in the same value.
Can anyone confirm that managed to get it working for more than 3 months from current time?
Or is there any official documentation addressing this?
It shows the data usage since last factory reset of your device.
May be the date that you are providing is older than your factory reset of your device.
hope i was helpful.
*i am get some data like this *
UsageStatsManager usageStatsManager = (UsageStatsManager) this.getSystemService("usagestats");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -1);
long start = calendar.getTimeInMillis();
long end = System.currentTimeMillis();
List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, start, end);
//Map<String,UsageStats> stats =usageStatsManager.queryAndAggregateUsageStats( start, end);
for (int i = 0; i < stats.size() ; i++)
{
Log.e(TAG,"<<<<"+i+">>>>"+"--------------------------------------------------------------------------");
Log.e(TAG,"Package Name = "+stats.get(i).getPackageName());
printt("First Time Stamp = ",stats.get(i).getFirstTimeStamp());
printt("Last Time Stamp = ",stats.get(i).getLastTimeStamp());
printt("Last Time Used = ",stats.get(i).getLastTimeUsed());
printt("Total Time Used in foreground = ",stats.get(i).getTotalTimeInForeground());
}
but how i calculate and show like this and how to i get app start time and end time from this available data
Hi I am tring to Create an app which add events to calendar. For example I need to create an event on every Saturday until dec 31ist.
The following are the attributes that I set for creating events,
event.put(CalendarContract.Events.CALENDAR_ID, 1);
event.put(CalendarContract.Events.TITLE, title);
event.put(CalendarContract.Events.DESCRIPTION, description);
event.put(CalendarContract.Events.EVENT_LOCATION, location);
event.put(CalendarContract.Events.DTSTART, sDate);
event.put(CalendarContract.Events.DURATION,"P50S");
event.put(CalendarContract.Events.ALL_DAY, 0);
event.put(CalendarContract.Events.HAS_ALARM, hasAlarm);
event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone);
event.put(CalendarContract.Events.RRULE, "FREQ=WEEKLY;BYDAY=SA;UNTIL=20151230");
mContext.getContentResolver().insert(baseUri, event);
But it create an event for the given date (sDate) and then create every Saturday. But how can I avoid that one event which created on given date (sDate)
I had the same problem. You need to check your reccurrence rule for day of week and offset your DTSTART to the nearest Saturday (or any other weekday that your recurrence rule contains). To give you rough example how to do that I'm attaching code from Android Calendar app that offsets start time and end time of the event based on reccurence rule string, and returns two long values - new start time and new end time if offset was applied, or null if it wasn't. EventRecurrence class can be found via search on GrepCode, its part of Android calendar app
public static long[] offsetStartTimeIfNecessary(long startMilis, long endMilis, String rrule) {
if (rrule == null || rrule.isEmpty() || rrule.replace("RRULE:", "").isEmpty()) {
// No need to waste any time with the parsing if the rule is empty.
return null;
}
long result[] = new long[2];
Calendar startTime = Calendar.getInstance();
startTime.setTimeInMillis(startMilis);
Calendar endTime = Calendar.getInstance();
endTime.setTimeInMillis(endMilis);
EventRecurrence mEventRecurrence = new EventRecurrence();
mEventRecurrence.parse(rrule.replace("RRULE:", ""));
// Check if we meet the specific special case. It has to:
// * be weekly
// * not recur on the same day of the week that the startTime falls on
// In this case, we'll need to push the start time to fall on the first day of the week
// that is part of the recurrence.
if (mEventRecurrence.freq != EventRecurrence.WEEKLY) {
// Not weekly so nothing to worry about.
return null;
}
if (mEventRecurrence.byday == null ||
mEventRecurrence.byday.length > mEventRecurrence.bydayCount) {
// This shouldn't happen, but just in case something is weird about the recurrence.
return null;
}
// Start to figure out what the nearest weekday is.
int closestWeekday = Integer.MAX_VALUE;
int weekstart = EventRecurrence.day2TimeDay(mEventRecurrence.wkst);
int startDay = startTime.get(Calendar.DAY_OF_WEEK) - 1;
for (int i = 0; i < mEventRecurrence.bydayCount; i++) {
int day = EventRecurrence.day2TimeDay(mEventRecurrence.byday[i]);
if (day == startDay) {
// Our start day is one of the recurring days, so we're good.
return null;
}
if (day < weekstart) {
// Let's not make any assumptions about what weekstart can be.
day += 7;
}
// We either want the earliest day that is later in the week than startDay ...
if (day > startDay && (day < closestWeekday || closestWeekday < startDay)) {
closestWeekday = day;
}
// ... or if there are no days later than startDay, we want the earliest day that is
// earlier in the week than startDay.
if (closestWeekday == Integer.MAX_VALUE || closestWeekday < startDay) {
// We haven't found a day that's later in the week than startDay yet.
if (day < closestWeekday) {
closestWeekday = day;
}
}
}
if (closestWeekday < startDay) {
closestWeekday += 7;
}
int daysOffset = closestWeekday - startDay;
startTime.add(Calendar.DAY_OF_MONTH, daysOffset);
endTime.add(Calendar.DAY_OF_MONTH, daysOffset);
result[0] = startTime.getTimeInMillis();
result[1] = endTime.getTimeInMillis();
return result;
}