Skip to content

Commit

Permalink
Common improvements (#17)
Browse files Browse the repository at this point in the history
* bf

* remove trash and remove applications usage tracking

* change order of settings showing
  • Loading branch information
yerseg authored Mar 6, 2021
1 parent 9b25a8b commit da2fa7c
Show file tree
Hide file tree
Showing 10 changed files with 18 additions and 193 deletions.
6 changes: 1 addition & 5 deletions profiling_app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,14 @@
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher_2"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_2_round"
android:supportsRtl="true"
android:theme="@style/Theme.Profiler"
android:fullBackupContent="@xml/backup_descriptor">
android:theme="@style/Theme.Profiler">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
Expand Down
40 changes: 9 additions & 31 deletions profiling_app/src/main/java/com/yerseg/profiler/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,15 @@ protected void onCreate(Bundle savedInstanceState) {
return;
}

if (shouldShowSettingsActivity(REQUEST_IGNORE_BATTERY_OPTIMIZATIONS_SHOWN)) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getApplicationContext().getPackageName()));
showLongToast("Allow the app to ignore battery optimizations please!");
startActivityForResult(intent, 1);
markSettingsActivityShown(REQUEST_IGNORE_BATTERY_OPTIMIZATIONS_SHOWN);
return;
}

// App settings
if (shouldShowSettingsActivity(APPLICATION_DETAILS_SETTINGS_SHOWN)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Expand All @@ -104,15 +113,6 @@ protected void onCreate(Bundle savedInstanceState) {
return;
}

if (shouldShowSettingsActivity(REQUEST_IGNORE_BATTERY_OPTIMIZATIONS_SHOWN)) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getApplicationContext().getPackageName()));
showLongToast("Allow the app to ignore battery optimizations please!");
startActivityForResult(intent, 1);
markSettingsActivityShown(REQUEST_IGNORE_BATTERY_OPTIMIZATIONS_SHOWN);
return;
}

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
showLongToast("Turn on WiFi please!");
Expand Down Expand Up @@ -231,28 +231,6 @@ public void onRequestPermissionsResult(int requestCode, String[] permissions, in
mIsPermissionsGranted = requestCode == PERMISSIONS_REQUEST_ID && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

private boolean shouldShowSettingsActivity(String preferencesKeyName) {
SharedPreferences prefs = getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
return !prefs.getBoolean(preferencesKeyName, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
Expand Down Expand Up @@ -46,6 +47,7 @@
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;

public class ProfilingService extends Service {
Expand All @@ -59,7 +61,6 @@ public class ProfilingService extends Service {

public static final int WIFI_STATS_UPDATE_FREQ = 5000;
public static final int BLUETOOTH_STATS_UPDATE_FREQ = 5000;
public static final int APP_STATS_UPDATE_FREQ = 5000;
public static final int LOCATION_STATS_UPDATE_FREQ = 5000;

public static final String PROFILING_STATS_DIRECTORY_NAME = "ProfilingData";
Expand Down Expand Up @@ -87,12 +88,10 @@ public class ProfilingService extends Service {
private HandlerThread mLocationProfilingThread;
private HandlerThread mWifiProfilingThread;
private HandlerThread mBluetoothProfilingThread;
private HandlerThread mApplicationProfilingThread;

private Handler mLocationProfilingThreadHandler;
private Handler mWifiProfilingThreadHandler;
private Handler mBluetoothProfilingThreadHandler;
private Handler mApplicationProfilingThreadHandler;

private BroadcastReceiver mWifiScanReceiver;
private BroadcastReceiver mBluetoothBroadcastReceiver;
Expand Down Expand Up @@ -121,7 +120,6 @@ public int onStartCommand(Intent intent, int flags, int startId) {
startLocationTracking();
startWifiTracking();
startBluetoothTracking();
startApplicationsStatisticTracking();
startAnyBroadcastsTracking();

PeriodicWorkRequest notifyWorkRequest = new PeriodicWorkRequest.Builder(ReminderNotificationPeriodicWorker.class, Duration.ofHours(2)).setInitialDelay(Duration.ofMinutes(5)).build();
Expand All @@ -142,7 +140,6 @@ public void onDestroy() {
stopLocationTracking();
stopWifiTracking();
stopBluetoothTracking();
stopApplicationsStatisticTracking();
stopAnyBroadcastsTracking();

WorkManager.getInstance(getApplicationContext()).cancelUniqueWork(PUSH_REMINDER_NOTIFICATION_WORK_TAG);
Expand Down Expand Up @@ -409,86 +406,19 @@ public void run() {
});
}

private void startApplicationsStatisticTracking() {
mApplicationProfilingThread = new HandlerThread("AppStatThread", Process.THREAD_PRIORITY_FOREGROUND);
mApplicationProfilingThread.start();

Looper looper = mApplicationProfilingThread.getLooper();
mApplicationProfilingThreadHandler = new Handler(looper);

mApplicationProfilingThreadHandler.post(new Runnable() {
@Override
public void run() {
try {
Utils.FileWriter.writeFile(Utils.getProfilingFilesDir(getApplicationContext()), ProfilingService.APP_STATS_FILE_NAME, getStatisticsForWritingToFile());
} catch (Exception ex) {
ex.printStackTrace();
}

mApplicationProfilingThreadHandler.postDelayed(this, APP_STATS_UPDATE_FREQ);
}

private String getStatisticsForWritingToFile() {
try {
long beginTime = java.lang.System.currentTimeMillis() - SystemClock.elapsedRealtime();
long endTime = java.lang.System.currentTimeMillis();

UsageStatsManager usageStatsManager = (UsageStatsManager) getApplicationContext().getSystemService(Context.USAGE_STATS_SERVICE);

String statResponseId = UUID.randomUUID().toString();
String timestamp = Utils.GetTimeStamp(endTime);

StringBuilder statistic = new StringBuilder();

List<UsageStats> usageStatsList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, beginTime, endTime);

for (UsageStats usageStats : usageStatsList) {
statistic.append(String.format(Locale.getDefault(), "%s;%s;UsageStats;%s;%d;%d;%d;%d\n",
timestamp,
statResponseId,
usageStats.getPackageName(),
usageStats.getFirstTimeStamp(),
usageStats.getLastTimeStamp(),
usageStats.getLastTimeUsed(),
usageStats.getTotalTimeInForeground()));
}

List<EventStats> eventStatsList = usageStatsManager.queryEventStats(UsageStatsManager.INTERVAL_DAILY, beginTime, endTime);

for (EventStats eventStat : eventStatsList) {
statistic.append(String.format(Locale.getDefault(), "%s;%s;EventStats;%d;%d;%d;%d;%d;%d\n",
timestamp,
statResponseId,
eventStat.getCount(),
eventStat.getEventType(),
eventStat.getFirstTimeStamp(),
eventStat.getLastTimeStamp(),
eventStat.getLastEventTime(),
eventStat.getTotalTime()));
}

return statistic.toString();
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
});
}

private void startAnyBroadcastsTracking() {
mAnyBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String intentType = intent.toString();
String intentAction = intent.getAction();

new Thread(() -> {
try {
String broadcastStats = String.format(Locale.getDefault(), "%s;%s;%s\n",
String broadcastStats = String.format(Locale.getDefault(), "%s;%s;%s;%s;%s;%s\n",
Utils.GetTimeStamp(System.currentTimeMillis()),
intentType,
intentAction);
intent.getAction(),
intent.getDataString(),
intent.getPackage(),
intent.getScheme(),
intent.getType());

Utils.FileWriter.writeFile(Utils.getProfilingFilesDir(getApplicationContext()), BROADCASTS_STATS_FILE_NAME, broadcastStats);
} catch (Exception ex) {
Expand Down Expand Up @@ -531,11 +461,6 @@ private void stopBluetoothTracking() {
mBluetoothProfilingThread.quit();
}

private void stopApplicationsStatisticTracking() {
mApplicationProfilingThreadHandler.removeCallbacksAndMessages(null);
mApplicationProfilingThread.quit();
}

private void stopAnyBroadcastsTracking() {
if (mAnyBroadcastReceiver != null)
unregisterReceiver(mAnyBroadcastReceiver);
Expand Down
1 change: 0 additions & 1 deletion profiling_app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@
android:id="@+id/SendDataByEmailButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/todo"
app:backgroundTint="@color/safe_green"
app:fabSize="auto"
app:layout_constraintBottom_toBottomOf="parent"
Expand Down
19 changes: 0 additions & 19 deletions profiling_app/src/main/res/layout/content_main.xml

This file was deleted.

10 changes: 0 additions & 10 deletions profiling_app/src/main/res/menu/menu_main.xml

This file was deleted.

28 changes: 0 additions & 28 deletions profiling_app/src/main/res/navigation/nav_graph.xml

This file was deleted.

3 changes: 0 additions & 3 deletions profiling_app/src/main/res/values/dimens.xml

This file was deleted.

9 changes: 0 additions & 9 deletions profiling_app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,15 +1,6 @@
<resources>
<string name="app_name">Profiler</string>
<string name="action_settings">Settings</string>
<!-- Strings used for fragments for navigation -->
<string name="first_fragment_label">First Fragment</string>
<string name="second_fragment_label">Second Fragment</string>
<string name="next">START</string>
<string name="previous">Previous</string>

<string name="Instruction">You can start and stop profiling by this buttons.</string>
<string name="hello_second_fragment">Hello second fragment. Arg: %1$s</string>
<string name="todo" />
<string name="buttonText">START</string>
<string name="stopButtonText">STOP</string>
</resources>
4 changes: 0 additions & 4 deletions profiling_app/src/main/res/xml/backup_descriptor.xml

This file was deleted.

0 comments on commit da2fa7c

Please sign in to comment.