Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
IshaanKr committed Aug 6, 2019
0 parents commit 3e4e9fe
Show file tree
Hide file tree
Showing 38 changed files with 1,008 additions and 0 deletions.
13 changes: 13 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
3 changes: 3 additions & 0 deletions .idea/dictionaries/ishaan.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions .idea/encodings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

52 changes: 52 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions .idea/runConfigurations.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
30 changes: 30 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
applicationId "com.xymenapps.usagestats"
minSdkVersion 22
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

api 'com.google.guava:guava:28.0-android'
}
21 changes: 21 additions & 0 deletions app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.xymenapps.usagestats;

import android.content.Context;

import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();

assertEquals("com.xymenapps.usagestats", appContext.getPackageName());
}
}
25 changes: 25 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.xymenapps.usagestats">

<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
146 changes: 146 additions & 0 deletions app/src/main/java/com/xymenapps/usagestats/MainActivity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
package com.xymenapps.usagestats;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AppOpsManager;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.provider.Settings;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.common.base.Joiner;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static android.app.AppOpsManager.MODE_ALLOWED;
import static android.app.AppOpsManager.OPSTR_GET_USAGE_STATS;

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getSimpleName();
String currentApp;
UsageStatsManager usm = null;
Map<String, String> appsOpened;
long todayInMs;
long hourToMs = 60 * 60 * 1000;
TextView result;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow(OPSTR_GET_USAGE_STATS, Process.myUid(), getPackageName());
boolean usage_permission = mode == MODE_ALLOWED;
appsOpened = new HashMap<>();
result = findViewById(R.id.result_textview);
result.setMovementMethod(new ScrollingMovementMethod());
result.setTextSize(15);

Calendar today = Calendar.getInstance();
long elapsed = today.get(Calendar.HOUR_OF_DAY) * 60 * 60 * 1000
+ today.get(Calendar.MINUTE) * 60 * 1000
+ today.get(Calendar.MILLISECOND) * 1000;
todayInMs = today.getTimeInMillis() - elapsed;
Log.d(TAG, "onCreate: Today in ms : " + todayInMs);
Log.d(TAG, "onCreate: Today: " + new Date(todayInMs));


if (usage_permission) {
Log.d(TAG, "onCreate: Permission granted");
usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
// findAppsOpened(System.currentTimeMillis() - 3600 * 1000, System.currentTimeMillis());
} else {
startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
Log.d(TAG, "onCreate: Permission denied");
Toast.makeText(this, "Grant access and relaunch activity", Toast.LENGTH_LONG).show();
}
}

private void findAppsOpened(long startTime, long endTime) {
Log.d(TAG, "findAppsOpened() called with: startTime = [" + startTime + "], endTime = [" + endTime + "]");
// List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
// if (appList != null && appList.size() > 0) {
// SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
// for (UsageStats usageStats : appList) {
// if (usageStats.getPackageName().equals(BuildConfig.APPLICATION_ID)) {
// Log.d(TAG, "First TimeStamp: " + new Date(usageStats.getFirstTimeStamp()));
// Log.d(TAG, "Last TimeStamp: " + new Date(usageStats.getLastTimeStamp()));
// Log.d(TAG, "Last Time Used: " + new Date(usageStats.getLastTimeUsed()));
// Log.d(TAG, "Totol foreground time: " + usageStats.getTotalTimeInForeground() / 1000 + " seconds");
// Log.d(TAG, "describeContents: " + usageStats.describeContents());
// }
// mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
// }
// if (mySortedMap != null && !mySortedMap.isEmpty()) {
// currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
// }
// Log.e("CURRENT APP", "Current App in foreground is: " + currentApp);
// }
Log.d(TAG, "findAppsOpened: FROM: " + new Date(startTime) + " TO: " + new Date(endTime));
try {
UsageEvents usageEvents = usm.queryEvents(startTime, endTime);
UsageEvents.Event event = new UsageEvents.Event();
while (usageEvents.hasNextEvent()) {
usageEvents.getNextEvent(event);
if (event.getEventType() == 1) {
String packageName = event.getPackageName();
long timestamp = event.getTimeStamp();
Calendar eventTime = Calendar.getInstance();
eventTime.setTimeInMillis(timestamp);
// Log.d(TAG, packageName + " : " + new Date(timestamp));
appsOpened.put(packageName, eventTime.get(Calendar.HOUR) + ":" + eventTime.get(Calendar.MINUTE) + " " + (eventTime.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM"));
}
}
displayResult();
} catch (NullPointerException e) {
Toast.makeText(this, "Error!!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}


private void displayResult() {
Log.d(TAG, "displayResult() called");
result.setText(Joiner.on("\n").withKeyValueSeparator(" : ").join(appsOpened));
}

public void find(View view) {
int id = view.getId();
switch (id) {
case R.id.button2:
findAppsOpened(todayInMs, todayInMs + 4 * hourToMs);
break;
case R.id.button3:
findAppsOpened(todayInMs + 4 * hourToMs, todayInMs + 8 * hourToMs);
break;
case R.id.button4:
findAppsOpened(todayInMs + 8 * hourToMs, todayInMs + 12 * hourToMs);
break;
case R.id.button5:
findAppsOpened(todayInMs + 12 * hourToMs, todayInMs + 16 * hourToMs);
break;
case R.id.button6:
findAppsOpened(todayInMs + 16 * hourToMs, todayInMs + 20 * hourToMs);
break;
case R.id.button7:
findAppsOpened(todayInMs + 20 * hourToMs, todayInMs + 24 * hourToMs);
break;
}
}
}
Loading

0 comments on commit 3e4e9fe

Please sign in to comment.