commit 296df1123887d115165d5d8ab2ff7a6fe8049761 Author: Nandan Desai Date: Thu Apr 9 16:28:54 2020 +0530 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..603b140 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +*.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 +.cxx diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..681f41a --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,116 @@ + + + + + + + +
+ + + + xmlns:android + + ^$ + + + +
+
+ + + + xmlns:.* + + ^$ + + + BY_NAME + +
+
+ + + + .*:id + + http://schemas.android.com/apk/res/android + + + +
+
+ + + + .*:name + + http://schemas.android.com/apk/res/android + + + +
+
+ + + + name + + ^$ + + + +
+
+ + + + style + + ^$ + + + +
+
+ + + + .* + + ^$ + + + BY_NAME + +
+
+ + + + .* + + http://schemas.android.com/apk/res/android + + + ANDROID_ATTRIBUTE_ORDER + +
+
+ + + + .* + + .* + + + BY_NAME + +
+
+
+
+
+
\ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..169fd0d --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,19 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..37a7509 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..7f68460 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..1c5a758 --- /dev/null +++ b/README.md @@ -0,0 +1,46 @@ +

+ +

+

PrivacyBreacher

+ +PrivacyBreacher is an Android app built as a proof of concept for a research article describing the privacy issues in Android. This app can access following information from your phone *without requesting any permissions*: + + 1. **Screen state of your phone (i.e., when your phone screen goes off/on)** + 2. **Monitor when you plug-in and remove your phone charger and wired headphones.** + 3. **Figure out at what time you switched on/off your phone (not directly implemented) .** + 4. **Access most of your device related information like your phone model, manufacturer etc.** + 5. **Keep track of your WiFi/Mobile data usage.** + 6. **Get a list of all the apps installed on your phone.** + 7. **Construct a 3D visualization of your body movements.** + +This app supports Android Pie (Android 9, API 28) or later versions. + +## Research Article + +To get more information on how this app can access all that data, check out our article here! + +## Screenshots + + + + +## Download + +Links will be provided soon! + +## Contribute + +We accept pull requests for this app. If you find any bugs or want to add new features or just want to improve the code structure, then pull requests are most welcome! + +## License + +MIT License + +Copyright 2020 DataBurn + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..7d82b4e --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,28 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 29 + buildToolsVersion "29.0.2" + defaultConfig { + applicationId "io.nandandesai.privacybreacher" + minSdkVersion 28 + targetSdkVersion 29 + 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.lifecycle:lifecycle-livedata:2.0.0" + implementation 'androidx.recyclerview:recyclerview:1.0.0' + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/app/proguard-rules.pro @@ -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 diff --git a/app/release/app-release.apk b/app/release/app-release.apk new file mode 100644 index 0000000..80cc40b Binary files /dev/null and b/app/release/app-release.apk differ diff --git a/app/release/output.json b/app/release/output.json new file mode 100644 index 0000000..c429e31 --- /dev/null +++ b/app/release/output.json @@ -0,0 +1 @@ +[{"outputType":{"type":"APK"},"apkData":{"type":"MAIN","splits":[],"versionCode":1,"versionName":"1.0","enabled":true,"outputFile":"app-release.apk","fullName":"release","baseName":"release"},"path":"app-release.apk","properties":{}}] \ No newline at end of file diff --git a/app/src/androidTest/java/io/nandandesai/privacybreacher/ExampleInstrumentedTest.java b/app/src/androidTest/java/io/nandandesai/privacybreacher/ExampleInstrumentedTest.java new file mode 100644 index 0000000..b2c3ee8 --- /dev/null +++ b/app/src/androidTest/java/io/nandandesai/privacybreacher/ExampleInstrumentedTest.java @@ -0,0 +1,27 @@ +package io.nandandesai.privacybreacher; + +import android.content.Context; + +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.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 Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + + assertEquals("io.nandandesai.privacybreacher", appContext.getPackageName()); + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..99e0627 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/ic_launcher-web.png b/app/src/main/ic_launcher-web.png new file mode 100644 index 0000000..13107ba Binary files /dev/null and b/app/src/main/ic_launcher-web.png differ diff --git a/app/src/main/java/io/nandandesai/privacybreacher/AboutActivity.java b/app/src/main/java/io/nandandesai/privacybreacher/AboutActivity.java new file mode 100644 index 0000000..c30d368 --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/AboutActivity.java @@ -0,0 +1,14 @@ +package io.nandandesai.privacybreacher; + +import androidx.appcompat.app.AppCompatActivity; + +import android.os.Bundle; + +public class AboutActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_about); + } +} diff --git a/app/src/main/java/io/nandandesai/privacybreacher/AppListRecyclerAdapter.java b/app/src/main/java/io/nandandesai/privacybreacher/AppListRecyclerAdapter.java new file mode 100644 index 0000000..6c9877f --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/AppListRecyclerAdapter.java @@ -0,0 +1,76 @@ +package io.nandandesai.privacybreacher; + +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +import java.util.ArrayList; + +public class AppListRecyclerAdapter extends RecyclerView.Adapter { + + private ArrayList apps; + private Context context; + + public AppListRecyclerAdapter(Context context, ArrayList apps) { + this.apps = apps; + this.context = context; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { + View view = LayoutInflater.from(context).inflate(R.layout.app_list_item, viewGroup, false); + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) { + App app = apps.get(position); + + viewHolder.appIcon.setImageDrawable(app.getIcon()); + viewHolder.appName.setText(app.getName()); + } + + @Override + public int getItemCount() { + return apps.size(); + } + + class ViewHolder extends RecyclerView.ViewHolder { + ImageView appIcon; + TextView appName; + + ViewHolder(@NonNull View itemView) { + super(itemView); + this.appIcon = itemView.findViewById(R.id.appIconImage); + this.appName = itemView.findViewById(R.id.appName); + } + } + + + public static class App { + private String name; + private Drawable icon; + + public App(String name, Drawable icon) { + this.name = name; + this.icon = icon; + } + + public String getName() { + return name; + } + + public Drawable getIcon() { + return icon; + } + } + +} diff --git a/app/src/main/java/io/nandandesai/privacybreacher/EventReceiver.java b/app/src/main/java/io/nandandesai/privacybreacher/EventReceiver.java new file mode 100644 index 0000000..298977d --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/EventReceiver.java @@ -0,0 +1,81 @@ +package io.nandandesai.privacybreacher; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.BatteryManager; +import android.util.Log; +import android.widget.Toast; + + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Locale; + + +public class EventReceiver extends BroadcastReceiver { + + private static final String TAG = "EventReceiver"; + + private ArrayList eventList = new ArrayList<>(); + + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + if (Intent.ACTION_SCREEN_ON.equals(action)) { + Log.i(TAG, "onReceive: Screen is active."); + eventList.add("\uD83D\uDD06 Phone screen turned ON at " + getFormattedDate(System.currentTimeMillis())); + PrivacyBreacherService.eventDatabase.setValue(eventList); + } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { + Log.i(TAG, "onReceive: Screen is inactive."); + eventList.add("\uD83D\uDD05 Phone screen turned OFF at " + getFormattedDate(System.currentTimeMillis())); + PrivacyBreacherService.eventDatabase.setValue(eventList); + } else if (Intent.ACTION_SHUTDOWN.equals(action)) { + Toast.makeText(context, "PrivacyBreacher just saw that you are switching OFF your phone!", Toast.LENGTH_LONG).show(); + } else if (Intent.ACTION_POWER_CONNECTED.equals(action)) { + Log.i(TAG, "onReceive: Phone charger is connected"); + IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); + Intent batteryStatus = context.registerReceiver(null, ifilter); + // How are we charging? + int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); + boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; + boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; + + if (usbCharge) { + eventList.add("⚡ You started charging your phone using USB cable connected to a laptop/PC at " + getFormattedDate(System.currentTimeMillis())); + PrivacyBreacherService.eventDatabase.setValue(eventList); + } else if (acCharge) { + eventList.add("\uD83D\uDD0C You started charging your phone using a Power Bank or AC Charging adapter at " + getFormattedDate(System.currentTimeMillis())); + PrivacyBreacherService.eventDatabase.setValue(eventList); + } + + Log.i(TAG, "usbCharge: " + usbCharge); + Log.i(TAG, "acCharging: " + acCharge); + } else if (Intent.ACTION_POWER_DISCONNECTED.equals(action)) { + Log.i(TAG, "onReceive: Phone charger is disconnected."); + eventList.add("\uD83D\uDD0B You disconnected your phone charger at " + getFormattedDate(System.currentTimeMillis())); + PrivacyBreacherService.eventDatabase.setValue(eventList); + } else if (Intent.ACTION_HEADSET_PLUG.equals(action)) { + if (!isInitialStickyBroadcast()) { + Log.i(TAG, "onReceive: Headphone action detected!"); + int state = intent.getIntExtra("state", -1); + if (state == 1) { + eventList.add("\uD83C\uDFA7 You plugged headphones at " + getFormattedDate(System.currentTimeMillis())); + PrivacyBreacherService.eventDatabase.setValue(eventList); + } else if (state == 0) { + eventList.add("\uD83D\uDD0A You unplugged headphones at " + getFormattedDate(System.currentTimeMillis())); + PrivacyBreacherService.eventDatabase.setValue(eventList); + } + } + } + + } + + private String getFormattedDate(long unixTime) { + SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss aa", Locale.US); + Date date = new Date(unixTime); + return formatter.format(date); + } +} diff --git a/app/src/main/java/io/nandandesai/privacybreacher/MainActivity.java b/app/src/main/java/io/nandandesai/privacybreacher/MainActivity.java new file mode 100644 index 0000000..e75d0f9 --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/MainActivity.java @@ -0,0 +1,114 @@ +package io.nandandesai.privacybreacher; + +import androidx.appcompat.app.AppCompatActivity; + +import android.app.ActivityManager; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.ImageButton; +import android.widget.PopupMenu; + +public class MainActivity extends AppCompatActivity { + + private static final String TAG = "MainActivity"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_main); + + if (!isMyServiceRunning(PrivacyBreacherService.class)) { + //start the foreground service + Intent serviceIntent = new Intent(this, PrivacyBreacherService.class); + startService(serviceIntent); + } + + //on click listeners + ImageButton optionsButton = findViewById(R.id.optionsButton); + optionsButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + showPopup(v); + } + }); + + Button physicalMonitorButton = findViewById(R.id.physicalMonitorButton); + physicalMonitorButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent intent = new Intent(MainActivity.this, PhysicalMonitorActivity.class); + startActivity(intent); + } + }); + + Button phoneMonitorButton = findViewById(R.id.phoneMonitorButton); + phoneMonitorButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent intent = new Intent(MainActivity.this, PhoneMonitorActivity.class); + startActivity(intent); + } + }); + + Button phoneInfoButton = findViewById(R.id.phoneInfoButton); + phoneInfoButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent intent = new Intent(MainActivity.this, PhoneInfoActivity.class); + startActivity(intent); + } + }); + + } + + public void showPopup(View v) { + PopupMenu popup = new PopupMenu(this, v); + MenuInflater inflater = popup.getMenuInflater(); + Menu menu = popup.getMenu(); + inflater.inflate(R.menu.home_menu, menu); + MenuItem aboutMenu = menu.findItem(R.id.menu_about); + aboutMenu.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { + @Override + public boolean onMenuItemClick(MenuItem item) { + + Intent intent = new Intent(MainActivity.this, AboutActivity.class); + startActivity(intent); + + return false; + } + }); + + MenuItem exitMenu = menu.findItem(R.id.menu_exit); + exitMenu.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { + @Override + public boolean onMenuItemClick(MenuItem item) { + exitApp(); + return false; + } + }); + popup.show(); + } + + private boolean isMyServiceRunning(Class serviceClass) { + ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if (serviceClass.getName().equals(service.service.getClassName())) { + return true; + } + } + return false; + } + + private void exitApp() { + Intent serviceIntent = new Intent(MainActivity.this, PrivacyBreacherService.class); + MainActivity.this.stopService(serviceIntent); + finish(); + } +} diff --git a/app/src/main/java/io/nandandesai/privacybreacher/PhoneInfoActivity.java b/app/src/main/java/io/nandandesai/privacybreacher/PhoneInfoActivity.java new file mode 100644 index 0000000..589106e --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/PhoneInfoActivity.java @@ -0,0 +1,189 @@ +package io.nandandesai.privacybreacher; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.recyclerview.widget.DividerItemDecoration; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.graphics.drawable.Drawable; +import android.net.TrafficStats; +import android.os.AsyncTask; +import android.os.Build; +import android.os.Bundle; +import android.os.SystemClock; +import android.util.Log; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.TextView; + +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +public class PhoneInfoActivity extends AppCompatActivity { + + private static final String TAG = "PhoneInfoActivity"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_phone_info); + new ActivityLoadTask(this).execute(); + } + + private static String getFormattedDataMeasure(long bytes) { + DecimalFormat decimalFormat = new DecimalFormat("#.#"); + String dataFormat = bytes + " B"; + float speed = 0; + if (bytes >= 1024) { + speed = bytes / 1024; //KB + speed = Float.valueOf(decimalFormat.format(speed)); + if (speed >= 1024) { + speed = speed / 1024; //MB + speed = Float.valueOf(decimalFormat.format(speed)); + if (speed >= 1024) { + speed = speed / 1024; //GB + speed = Float.valueOf(decimalFormat.format(speed)); + dataFormat = speed + " GB"; + } else { + dataFormat = speed + " MB"; + } + } else { + dataFormat = speed + " KB"; + } + } + + return dataFormat; + } + + private static class ActivityLoadTask extends AsyncTask { + + private TextView productView; + private TextView modelView; + private TextView manufacturerView; + private TextView manufacturedOn; + private TextView brandView; + private TextView deviceView; + private TextView deviceUptimeView; + private TextView mobileDataView; + private TextView wifiDataView; + + private RecyclerView appListRecyclerView; + + private LinearLayout phoneInfoView; + private ProgressBar progressBar; + + //Build + private String product; + private String model; + private String manufacturer; + private String buildTime; + private String brand; + private String device; + + //uptime + private String uptimeString; + + //data used + private long mobileDataUsed; + private long wifiDataUsed; + + //apps installed + private ArrayList apps = new ArrayList<>(); + + private AppCompatActivity activity; + + ActivityLoadTask(AppCompatActivity activity) { + this.activity = activity; + productView = activity.findViewById(R.id.product); + modelView = activity.findViewById(R.id.model); + manufacturerView = activity.findViewById(R.id.manufacturer); + manufacturedOn = activity.findViewById(R.id.manufacturedOn); + brandView = activity.findViewById(R.id.brand); + deviceView = activity.findViewById(R.id.device); + deviceUptimeView = activity.findViewById(R.id.deviceUptime); + mobileDataView = activity.findViewById(R.id.mobileDataUsed); + wifiDataView = activity.findViewById(R.id.wifiDataUsed); + + appListRecyclerView = activity.findViewById(R.id.appListRecyclerView); + + phoneInfoView = activity.findViewById(R.id.phoneInfoView); + progressBar = activity.findViewById(R.id.progressBar); + } + + @Override + protected void onPreExecute() { + phoneInfoView.setVisibility(View.INVISIBLE); + progressBar.setVisibility(View.VISIBLE); + } + + @Override + protected Void doInBackground(Void... voids) { + + //build info + product = Build.PRODUCT; + model = Build.MODEL; + manufacturer = Build.MANUFACTURER; + buildTime = new Date(Build.TIME).toString(); + brand = Build.BRAND; + device = Build.DEVICE; + + //SystemClock, get the uptime of the device since boot + long uptime = SystemClock.uptimeMillis(); + SimpleDateFormat formatter = new SimpleDateFormat("dd:HH:mm:ss", Locale.ENGLISH); + Date date = new Date(uptime); + uptimeString = formatter.format(date); + + //Data used + mobileDataUsed = TrafficStats.getMobileRxBytes() + TrafficStats.getTotalTxBytes(); + long totalDataUsed = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes(); + wifiDataUsed = totalDataUsed - mobileDataUsed; + + //apps installed + final PackageManager pm = activity.getPackageManager(); + List packages = pm.getInstalledApplications(PackageManager.GET_META_DATA); + + for (ApplicationInfo packageInfo : packages) { + String appName = pm.getApplicationLabel(packageInfo).toString(); + Drawable appIcon = pm.getApplicationIcon(packageInfo); + apps.add(new AppListRecyclerAdapter.App(appName, appIcon)); + } + + return null; + } + + @Override + protected void onPostExecute(Void voids) { + + productView.setText(product); + modelView.setText(model); + manufacturerView.setText(manufacturer); + manufacturedOn.setText(buildTime); + brandView.setText(brand); + deviceView.setText(device); + deviceUptimeView.setText(uptimeString + " in (dd:hh:mm:ss) format"); + mobileDataView.setText(getFormattedDataMeasure(mobileDataUsed)); + wifiDataView.setText(getFormattedDataMeasure(wifiDataUsed)); + + LinearLayoutManager layoutManager = new LinearLayoutManager(activity); + appListRecyclerView.setLayoutManager(layoutManager); + DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(appListRecyclerView.getContext(), layoutManager.getOrientation()); + appListRecyclerView.addItemDecoration(dividerItemDecoration); + + appListRecyclerView.setNestedScrollingEnabled(false); + appListRecyclerView.setFocusable(false); + + AppListRecyclerAdapter appListRecyclerAdapter = new AppListRecyclerAdapter(activity, apps); + appListRecyclerView.setAdapter(appListRecyclerAdapter); + + phoneInfoView.setVisibility(View.VISIBLE); + progressBar.setVisibility(View.INVISIBLE); + } + } +} diff --git a/app/src/main/java/io/nandandesai/privacybreacher/PhoneLogRecyclerAdapter.java b/app/src/main/java/io/nandandesai/privacybreacher/PhoneLogRecyclerAdapter.java new file mode 100644 index 0000000..babe651 --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/PhoneLogRecyclerAdapter.java @@ -0,0 +1,56 @@ +package io.nandandesai.privacybreacher; + +import android.content.Context; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +import java.util.ArrayList; + +public class PhoneLogRecyclerAdapter extends RecyclerView.Adapter { + private static final String TAG = "PhoneLogRecyclerAdapter"; + private Context context; + private ArrayList logEntries; + + PhoneLogRecyclerAdapter(Context context, ArrayList logEntries) { + this.context = context; + this.logEntries = logEntries; + } + + void setLogEntries(ArrayList logEntries) { + this.logEntries = logEntries; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { + View view = LayoutInflater.from(context).inflate(R.layout.phone_monitor_log_item, viewGroup, false); + ViewHolder viewHolder = new ViewHolder(view); + return viewHolder; + } + + @Override + public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) { + Log.i(TAG, "onBindViewHolder: Adding log entry to TextView: " + logEntries.get(position)); + viewHolder.phoneMonitorLogItem.setText(logEntries.get(position)); + } + + @Override + public int getItemCount() { + return logEntries.size(); + } + + class ViewHolder extends RecyclerView.ViewHolder { + TextView phoneMonitorLogItem; + + ViewHolder(@NonNull View itemView) { + super(itemView); + phoneMonitorLogItem = itemView.findViewById(R.id.phoneMonitorLogItem); + } + } +} diff --git a/app/src/main/java/io/nandandesai/privacybreacher/PhoneMonitorActivity.java b/app/src/main/java/io/nandandesai/privacybreacher/PhoneMonitorActivity.java new file mode 100644 index 0000000..b08f6e8 --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/PhoneMonitorActivity.java @@ -0,0 +1,62 @@ +package io.nandandesai.privacybreacher; + +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.lifecycle.Observer; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import android.content.DialogInterface; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.TextView; + +import java.util.ArrayList; + +public class PhoneMonitorActivity extends AppCompatActivity { + + private static final String TAG = "PhoneMonitorActivity"; + private PhoneLogRecyclerAdapter phoneLogRecyclerAdapter; + private RecyclerView phoneLogRecyclerView; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_phone_monitor); + + phoneLogRecyclerView = findViewById(R.id.phoneLogRecyclerView); + LinearLayoutManager layoutManager = new LinearLayoutManager(this); + phoneLogRecyclerView.setLayoutManager(layoutManager); + phoneLogRecyclerAdapter = new PhoneLogRecyclerAdapter(this, new ArrayList()); + phoneLogRecyclerView.setAdapter(phoneLogRecyclerAdapter); + + final TextView noLogText = findViewById(R.id.noLogText); + final TextView headingText = findViewById(R.id.headingText); + headingText.setVisibility(View.INVISIBLE); + PrivacyBreacherService.eventDatabase.observe(this, new Observer>() { + @Override + public void onChanged(ArrayList logEntries) { + Log.i(TAG, "onChanged: event change received in PhoneMonitorActivity"); + noLogText.setVisibility(View.INVISIBLE); + headingText.setVisibility(View.VISIBLE); + Log.i(TAG, "LogEntries: " + logEntries); + phoneLogRecyclerAdapter.setLogEntries(logEntries); + phoneLogRecyclerAdapter.notifyDataSetChanged(); + phoneLogRecyclerView.scrollToPosition(phoneLogRecyclerAdapter.getItemCount() - 1); + } + }); + + AlertDialog.Builder alertDialog = new AlertDialog.Builder(this, R.style.AlertDialogCustom); + alertDialog.setTitle("Phone activity monitoring"); + alertDialog.setMessage("Apps installed on your phone can monitor when you turn ON/OFF your screen without requesting any permissions. This way, they can know how many hours you used your phone today, from what time to what time you used your phone," + + " how many times you charge your phone and are you charging with your Power Bank or AC Charging socket etc. This loophole can help bad guys build a pretty good spyware for your phone!"); + alertDialog.setCancelable(false); + alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.dismiss(); + } + }); + alertDialog.show(); + } +} diff --git a/app/src/main/java/io/nandandesai/privacybreacher/PhysicalMonitorActivity.java b/app/src/main/java/io/nandandesai/privacybreacher/PhysicalMonitorActivity.java new file mode 100644 index 0000000..a0c6ec8 --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/PhysicalMonitorActivity.java @@ -0,0 +1,76 @@ +package io.nandandesai.privacybreacher; + +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; + +import android.app.ActivityManager; +import android.content.Context; +import android.content.DialogInterface; +import android.content.pm.ConfigurationInfo; +import android.opengl.GLSurfaceView; +import android.os.Bundle; + +public class PhysicalMonitorActivity extends AppCompatActivity { + + /** + * Hold a reference to our GLSurfaceView + */ + private GLSurfaceView mGLSurfaceView; + private SensorFusion mSensorFusion; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + AlertDialog.Builder alertDialog = new AlertDialog.Builder(this, R.style.AlertDialogCustom); + alertDialog.setTitle("Physical activity monitoring"); + alertDialog.setMessage("Apps installed on your phone can monitor the angle at which you are holding your phone, the direction in which you are holding your phone, speed at which you are moving your phone etc. using Gyroscope, Accelerometer and Magnetometer sensors without your permission." + + "This can give them a 3D visualization of your hand & body movements. This is a huge privacy loophole.\n\nGo ahead and see how this app visualizes your movements without any permissions. Start moving your phone!"); + alertDialog.setCancelable(false); + alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.dismiss(); + } + }); + alertDialog.show(); + + mSensorFusion = new SensorFusion(this); + mGLSurfaceView = new GLSurfaceView(this); + + // Check if the system supports OpenGL ES 2.0. + final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); + final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000; + + if (supportsEs2) { + // Request an OpenGL ES 2.0 compatible context. + mGLSurfaceView.setEGLContextClientVersion(2); + + // Set the renderer to our demo renderer, defined below. + mGLSurfaceView.setRenderer(new Renderer(mSensorFusion)); + + + //mGLSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); + } else { + // This is where you could create an OpenGL ES 1.x compatible + // renderer if you wanted to support both ES 1 and ES 2. + return; + } + + setContentView(mGLSurfaceView); + } + + @Override + protected void onResume() { + // The activity must call the GL surface view's onResume() on activity onResume(). + super.onResume(); + mGLSurfaceView.onResume(); + } + + @Override + protected void onPause() { + // The activity must call the GL surface view's onPause() on activity onPause(). + super.onPause(); + mGLSurfaceView.onPause(); + } +} diff --git a/app/src/main/java/io/nandandesai/privacybreacher/PrivacyBreacherService.java b/app/src/main/java/io/nandandesai/privacybreacher/PrivacyBreacherService.java new file mode 100644 index 0000000..27d733f --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/PrivacyBreacherService.java @@ -0,0 +1,78 @@ +package io.nandandesai.privacybreacher; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.IBinder; + +import androidx.core.app.NotificationCompat; +import androidx.lifecycle.MutableLiveData; + +import java.util.ArrayList; + +public class PrivacyBreacherService extends Service { + + private static final String TAG = "PrivacyBreacherService"; + + public static MutableLiveData> eventDatabase = new MutableLiveData<>(); + + private EventReceiver eventReceiver; + + public PrivacyBreacherService() { + } + + @Override + public IBinder onBind(Intent intent) { + return null; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + startForeground(R.string.app_name, getNotification(this)); + + IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON); + intentFilter.addAction(Intent.ACTION_SCREEN_OFF); + intentFilter.addAction(Intent.ACTION_SHUTDOWN); + intentFilter.addAction(Intent.ACTION_POWER_CONNECTED); + intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED); + intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); + eventReceiver = new EventReceiver(); + registerReceiver(eventReceiver, intentFilter); + + return START_STICKY; + } + + @Override + public void onDestroy() { + unregisterReceiver(eventReceiver); + eventDatabase = null; //garbage collect that object + } + + public Notification getNotification(Context context) { + + Intent mainActivityIntent = new Intent(context, MainActivity.class); + PendingIntent pendingNotificationIntent = PendingIntent.getActivity(context, 0, mainActivityIntent, 0); + + NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + final String NOTIF_CHANNEL_ID = "privacybreacher"; + final String NOTIF_CHANNEL_NAME = "PrivacyBreacher"; + NotificationChannel channel = new NotificationChannel(NOTIF_CHANNEL_ID, NOTIF_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH); + notificationManager.createNotificationChannel(channel); + + NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIF_CHANNEL_ID) + .setContentTitle("PrivacyBreacher is running!") + .setContentText("PrivacyBreacher is monitoring your activities.") + .setPriority(2) + .setDefaults(Notification.FLAG_FOREGROUND_SERVICE) + .setSmallIcon(R.drawable.ic_stat_name) + .setShowWhen(false) + .setOngoing(true) + .setContentIntent(pendingNotificationIntent); + return notificationBuilder.build(); + } +} diff --git a/app/src/main/java/io/nandandesai/privacybreacher/Renderer.java b/app/src/main/java/io/nandandesai/privacybreacher/Renderer.java new file mode 100644 index 0000000..61d4f56 --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/Renderer.java @@ -0,0 +1,460 @@ +package io.nandandesai.privacybreacher; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL10; + +import android.opengl.GLES20; +import android.opengl.GLSurfaceView; +import android.opengl.Matrix; +import android.util.Log; + +/** + * This class implements our custom renderer. Note that the GL10 parameter passed in is unused for OpenGL ES 2.0 + * renderers -- the static class GLES20 is used instead. + */ +public class Renderer implements GLSurfaceView.Renderer { + /** + * Used for debug logs. + */ + private static final String TAG = "Renderer"; + + /** + * Store the model matrix. This matrix is used to move models from object space (where each model can be thought + * of being located at the center of the universe) to world space. + */ + private float[] mModelMatrix = new float[16]; + + /** + * Store the view matrix. This can be thought of as our camera. This matrix transforms world space to eye space; + * it positions things relative to our eye. + */ + private float[] mViewMatrix = new float[16]; + + /** + * Store the projection matrix. This is used to project the scene onto a 2D viewport. + */ + private float[] mProjectionMatrix = new float[16]; + + /** + * Allocate storage for the final combined matrix. This will be passed into the shader program. + */ + private float[] mMVPMatrix = new float[16]; + + /** + * Store our model data in a float buffer. + */ + private final FloatBuffer mCubePositions; + private final FloatBuffer mCubeColors; + + /** + * This will be used to pass in the transformation matrix. + */ + private int mMVPMatrixHandle; + + /** + * This will be used to pass in the modelview matrix. + */ + private int mMVMatrixHandle; + + /** + * This will be used to pass in model position information. + */ + private int mPositionHandle; + + /** + * This will be used to pass in model color information. + */ + private int mColorHandle; + + /** + * How many bytes per float. + */ + private final int mBytesPerFloat = 4; + + /** + * Size of the position data in elements. + */ + private final int mPositionDataSize = 3; + + /** + * Size of the color data in elements. + */ + private final int mColorDataSize = 4; + + /** + * This is a handle to our per-vertex cube shading program. + */ + private int mPerVertexProgramHandle; + + private SensorFusion mSensorFusion; + + /** + * Initialize the model data. + */ + public Renderer(SensorFusion sensorFusion) { + mSensorFusion = sensorFusion; + + // Define points for a cube. + + // X, Y, Z + final float[] cubePositionData = + { + // In OpenGL counter-clockwise winding is default. This means that when we look at a triangle, + // if the points are counter-clockwise we are looking at the "front". If not we are looking at + // the back. OpenGL has an optimization where all back-facing triangles are culled, since they + // usually represent the backside of an object and aren't visible anyways. + + // Front face + -1.0f, 1.0f, 1.0f, + -1.0f, -1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, + -1.0f, -1.0f, 1.0f, + 1.0f, -1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, + + // Right face + 1.0f, 1.0f, 1.0f, + 1.0f, -1.0f, 1.0f, + 1.0f, 1.0f, -1.0f, + 1.0f, -1.0f, 1.0f, + 1.0f, -1.0f, -1.0f, + 1.0f, 1.0f, -1.0f, + + // Back face + 1.0f, 1.0f, -1.0f, + 1.0f, -1.0f, -1.0f, + -1.0f, 1.0f, -1.0f, + 1.0f, -1.0f, -1.0f, + -1.0f, -1.0f, -1.0f, + -1.0f, 1.0f, -1.0f, + + // Left face + -1.0f, 1.0f, -1.0f, + -1.0f, -1.0f, -1.0f, + -1.0f, 1.0f, 1.0f, + -1.0f, -1.0f, -1.0f, + -1.0f, -1.0f, 1.0f, + -1.0f, 1.0f, 1.0f, + + // Top face + -1.0f, 1.0f, -1.0f, + -1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, -1.0f, + -1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, -1.0f, + + // Bottom face + 1.0f, -1.0f, -1.0f, + 1.0f, -1.0f, 1.0f, + -1.0f, -1.0f, -1.0f, + 1.0f, -1.0f, 1.0f, + -1.0f, -1.0f, 1.0f, + -1.0f, -1.0f, -1.0f, + }; + + // R, G, B, A + final float[] cubeColorData = + { + // Front face (red) + 1.0f, 0.0f, 0.0f, 1.0f, + 1.0f, 0.0f, 0.0f, 1.0f, + 1.0f, 0.0f, 0.0f, 1.0f, + 1.0f, 0.0f, 0.0f, 1.0f, + 1.0f, 0.0f, 0.0f, 1.0f, + 1.0f, 0.0f, 0.0f, 1.0f, + + // Right face (green) + 0.0f, 1.0f, 0.0f, 1.0f, + 0.0f, 1.0f, 0.0f, 1.0f, + 0.0f, 1.0f, 0.0f, 1.0f, + 0.0f, 1.0f, 0.0f, 1.0f, + 0.0f, 1.0f, 0.0f, 1.0f, + 0.0f, 1.0f, 0.0f, 1.0f, + + // Back face (blue) + 0.0f, 0.0f, 1.0f, 1.0f, + 0.0f, 0.0f, 1.0f, 1.0f, + 0.0f, 0.0f, 1.0f, 1.0f, + 0.0f, 0.0f, 1.0f, 1.0f, + 0.0f, 0.0f, 1.0f, 1.0f, + 0.0f, 0.0f, 1.0f, 1.0f, + + // Left face (yellow) + 1.0f, 1.0f, 0.0f, 1.0f, + 1.0f, 1.0f, 0.0f, 1.0f, + 1.0f, 1.0f, 0.0f, 1.0f, + 1.0f, 1.0f, 0.0f, 1.0f, + 1.0f, 1.0f, 0.0f, 1.0f, + 1.0f, 1.0f, 0.0f, 1.0f, + + // Top face (cyan) + 0.0f, 1.0f, 1.0f, 1.0f, + 0.0f, 1.0f, 1.0f, 1.0f, + 0.0f, 1.0f, 1.0f, 1.0f, + 0.0f, 1.0f, 1.0f, 1.0f, + 0.0f, 1.0f, 1.0f, 1.0f, + 0.0f, 1.0f, 1.0f, 1.0f, + + // Bottom face (magenta) + 1.0f, 0.0f, 1.0f, 1.0f, + 1.0f, 0.0f, 1.0f, 1.0f, + 1.0f, 0.0f, 1.0f, 1.0f, + 1.0f, 0.0f, 1.0f, 1.0f, + 1.0f, 0.0f, 1.0f, 1.0f, + 1.0f, 0.0f, 1.0f, 1.0f + }; + + // Initialize the buffers. + mCubePositions = ByteBuffer.allocateDirect(cubePositionData.length * mBytesPerFloat) + .order(ByteOrder.nativeOrder()).asFloatBuffer(); + mCubePositions.put(cubePositionData).position(0); + + mCubeColors = ByteBuffer.allocateDirect(cubeColorData.length * mBytesPerFloat) + .order(ByteOrder.nativeOrder()).asFloatBuffer(); + mCubeColors.put(cubeColorData).position(0); + } + + private String getVertexShader() { + final String vertexShader = + "uniform mat4 u_MVPMatrix; \n" // A constant representing the combined model/view/projection matrix. + + "uniform mat4 u_MVMatrix; \n" // A constant representing the combined model/view matrix. + + + "attribute vec4 a_Position; \n" // Per-vertex position information we will pass in. + + "attribute vec4 a_Color; \n" // Per-vertex color information we will pass in. + + + "varying vec4 v_Color; \n" // This will be passed into the fragment shader. + + + "void main() \n" // The entry point for our vertex shader. + + "{ \n" + // Transform the vertex into eye space. + + " vec3 modelViewVertex = vec3(u_MVMatrix * a_Position); \n" + // Multiply the color by the illumination level. It will be interpolated across the triangle. + + " v_Color = a_Color; \n" + // gl_Position is a special variable used to store the final position. + // Multiply the vertex by the matrix to get the final point in normalized screen coordinates. + + " gl_Position = u_MVPMatrix * a_Position; \n" + + "} \n"; + + return vertexShader; + } + + private String getFragmentShader() { + final String fragmentShader = + "precision mediump float; \n" // Set the default precision to medium. We don't need as high of a + // precision in the fragment shader. + + "varying vec4 v_Color; \n" // This is the color from the vertex shader interpolated across the + // triangle per fragment. + + "void main() \n" // The entry point for our fragment shader. + + "{ \n" + + " gl_FragColor = v_Color; \n" // Pass the color directly through the pipeline. + + "} \n"; + + return fragmentShader; + } + + @Override + public void onSurfaceCreated(GL10 glUnused, EGLConfig config) { + // Set the background clear color to black. + GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + + // Use culling to remove back faces. + GLES20.glEnable(GLES20.GL_CULL_FACE); + + // Enable depth testing + GLES20.glEnable(GLES20.GL_DEPTH_TEST); + + // Position the eye in front of the origin. + final float eyeX = 0.0f; + final float eyeY = 0.0f; + final float eyeZ = -0.5f; + + // We are looking toward the distance + final float lookX = 0.0f; + final float lookY = 0.0f; + final float lookZ = -5.0f; + + // Set our up vector. This is where our head would be pointing were we holding the camera. + final float upX = 0.0f; + final float upY = 1.0f; + final float upZ = 0.0f; + + // Set the view matrix. This matrix can be said to represent the camera position. + // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and + // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose. + Matrix.setLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ); + + final String vertexShader = getVertexShader(); + final String fragmentShader = getFragmentShader(); + + final int vertexShaderHandle = compileShader(GLES20.GL_VERTEX_SHADER, vertexShader); + final int fragmentShaderHandle = compileShader(GLES20.GL_FRAGMENT_SHADER, fragmentShader); + + mPerVertexProgramHandle = createAndLinkProgram(vertexShaderHandle, fragmentShaderHandle, + new String[]{"a_Position", "a_Color"}); + } + + @Override + public void onSurfaceChanged(GL10 glUnused, int width, int height) { + // Set the OpenGL viewport to the same size as the surface. + GLES20.glViewport(0, 0, width, height); + + // Create a new perspective projection matrix. The height will stay the same + // while the width will vary as per aspect ratio. + final float ratio = (float) width / height; + final float left = -ratio; + final float right = ratio; + final float bottom = -1.0f; + final float top = 1.0f; + final float near = 1.0f; + final float far = 10.0f; + + Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far); + } + + @Override + public void onDrawFrame(GL10 glUnused) { + GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); + + // Set our per-vertex lighting program. + GLES20.glUseProgram(mPerVertexProgramHandle); + + // Set program handles for cube drawing. + mMVPMatrixHandle = GLES20.glGetUniformLocation(mPerVertexProgramHandle, "u_MVPMatrix"); + mMVMatrixHandle = GLES20.glGetUniformLocation(mPerVertexProgramHandle, "u_MVMatrix"); + mPositionHandle = GLES20.glGetAttribLocation(mPerVertexProgramHandle, "a_Position"); + mColorHandle = GLES20.glGetAttribLocation(mPerVertexProgramHandle, "a_Color"); + + // Draw some cubes. + Matrix.setIdentityM(mModelMatrix, 0); + Matrix.translateM(mModelMatrix, 0, 0.0f, 0.0f, -5.0f); + Matrix.rotateM(mModelMatrix, 0, (float) Math.toDegrees(-mSensorFusion.fusedOrientation[1]), 1.0f, 0.0f, 0.0f); // pitch + Matrix.rotateM(mModelMatrix, 0, (float) Math.toDegrees(mSensorFusion.fusedOrientation[2]), 0.0f, 1.0f, 0.0f); // roll + Matrix.rotateM(mModelMatrix, 0, (float) Math.toDegrees(mSensorFusion.fusedOrientation[0]), 0.0f, 0.0f, 1.0f); // yaw + drawCube(); + } + + /** + * Draws a cube. + */ + private void drawCube() { + // Pass in the position information + mCubePositions.position(0); + GLES20.glVertexAttribPointer(mPositionHandle, mPositionDataSize, GLES20.GL_FLOAT, false, + 0, mCubePositions); + + GLES20.glEnableVertexAttribArray(mPositionHandle); + + // Pass in the color information + mCubeColors.position(0); + GLES20.glVertexAttribPointer(mColorHandle, mColorDataSize, GLES20.GL_FLOAT, false, + 0, mCubeColors); + + GLES20.glEnableVertexAttribArray(mColorHandle); + + // This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix + // (which currently contains model * view). + Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0); + + // Pass in the modelview matrix. + GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, mMVPMatrix, 0); + + // This multiplies the modelview matrix by the projection matrix, and stores the result in the MVP matrix + // (which now contains model * view * projection). + Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0); + + // Pass in the combined matrix. + GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0); + + // Draw the cube. + GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 36); + } + + /** + * Helper function to compile a shader. + * + * @param shaderType The shader type. + * @param shaderSource The shader source code. + * @return An OpenGL handle to the shader. + */ + private int compileShader(final int shaderType, final String shaderSource) { + int shaderHandle = GLES20.glCreateShader(shaderType); + + if (shaderHandle != 0) { + // Pass in the shader source. + GLES20.glShaderSource(shaderHandle, shaderSource); + + // Compile the shader. + GLES20.glCompileShader(shaderHandle); + + // Get the compilation status. + final int[] compileStatus = new int[1]; + GLES20.glGetShaderiv(shaderHandle, GLES20.GL_COMPILE_STATUS, compileStatus, 0); + + // If the compilation failed, delete the shader. + if (compileStatus[0] == 0) { + Log.e(TAG, "Error compiling shader: " + GLES20.glGetShaderInfoLog(shaderHandle)); + GLES20.glDeleteShader(shaderHandle); + shaderHandle = 0; + } + } + + if (shaderHandle == 0) { + throw new RuntimeException("Error creating shader."); + } + + return shaderHandle; + } + + /** + * Helper function to compile and link a program. + * + * @param vertexShaderHandle An OpenGL handle to an already-compiled vertex shader. + * @param fragmentShaderHandle An OpenGL handle to an already-compiled fragment shader. + * @param attributes Attributes that need to be bound to the program. + * @return An OpenGL handle to the program. + */ + private int createAndLinkProgram(final int vertexShaderHandle, final int fragmentShaderHandle, final String[] attributes) { + int programHandle = GLES20.glCreateProgram(); + + if (programHandle != 0) { + // Bind the vertex shader to the program. + GLES20.glAttachShader(programHandle, vertexShaderHandle); + + // Bind the fragment shader to the program. + GLES20.glAttachShader(programHandle, fragmentShaderHandle); + + // Bind attributes + if (attributes != null) { + final int size = attributes.length; + for (int i = 0; i < size; i++) { + GLES20.glBindAttribLocation(programHandle, i, attributes[i]); + } + } + + // Link the two shaders together into a program. + GLES20.glLinkProgram(programHandle); + + // Get the link status. + final int[] linkStatus = new int[1]; + GLES20.glGetProgramiv(programHandle, GLES20.GL_LINK_STATUS, linkStatus, 0); + + // If the link failed, delete the program. + if (linkStatus[0] == 0) { + Log.e(TAG, "Error compiling program: " + GLES20.glGetProgramInfoLog(programHandle)); + GLES20.glDeleteProgram(programHandle); + programHandle = 0; + } + } + + if (programHandle == 0) { + throw new RuntimeException("Error creating program."); + } + + return programHandle; + } +} diff --git a/app/src/main/java/io/nandandesai/privacybreacher/SensorFusion.java b/app/src/main/java/io/nandandesai/privacybreacher/SensorFusion.java new file mode 100644 index 0000000..610b547 --- /dev/null +++ b/app/src/main/java/io/nandandesai/privacybreacher/SensorFusion.java @@ -0,0 +1,344 @@ +package io.nandandesai.privacybreacher; + +/************************************************************************************ + * Copyright (c) 2012 Paul Lawitzki + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE + * OR OTHER DEALINGS IN THE SOFTWARE. + ************************************************************************************/ + + +import android.content.Context; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; + +import java.util.Timer; +import java.util.TimerTask; + +public class SensorFusion implements SensorEventListener { + + private SensorManager mSensorManager = null; + + // angular speeds from gyro + private float[] gyro = new float[3]; + + // rotation matrix from gyro data + private float[] gyroMatrix = new float[9]; + + // orientation angles from gyro matrix + private float[] gyroOrientation = new float[3]; + + // magnetic field vector + private float[] magnet = new float[3]; + + // accelerometer vector + private float[] accel = new float[3]; + + // orientation angles from accel and magnet + private float[] accMagOrientation = new float[3]; + + // final orientation angles from sensor fusion + float[] fusedOrientation = new float[3]; + + // accelerometer and magnetometer based rotation matrix + private float[] rotationMatrix = new float[9]; + + private static final float EPSILON = 0.000000001f; + private static final float NS2S = 1.0f / 1000000000.0f; + private long timestamp; + private boolean initState = true; + + private static final int TIME_CONSTANT = 30; + private static final float FILTER_COEFFICIENT = 0.98f; + private Timer fuseTimer = new Timer(); + + private Context mContext; + + SensorFusion(Context context) { + mContext = context; + + gyroOrientation[0] = 0.0f; + gyroOrientation[1] = 0.0f; + gyroOrientation[2] = 0.0f; + + // initialise gyroMatrix with identity matrix + gyroMatrix[0] = 1.0f; + gyroMatrix[1] = 0.0f; + gyroMatrix[2] = 0.0f; + gyroMatrix[3] = 0.0f; + gyroMatrix[4] = 1.0f; + gyroMatrix[5] = 0.0f; + gyroMatrix[6] = 0.0f; + gyroMatrix[7] = 0.0f; + gyroMatrix[8] = 1.0f; + + // get sensorManager and initialise sensor listeners + mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); + initListeners(); + + // wait for one second until gyroscope and magnetometer/accelerometer + // data is initialised then scedule the complementary filter task + fuseTimer.scheduleAtFixedRate(new calculateFusedOrientationTask(), + 1000, TIME_CONSTANT); + + } + + // This function registers sensor listeners for the accelerometer, magnetometer and gyroscope. + private void initListeners() { + mSensorManager.registerListener(this, + mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), + SensorManager.SENSOR_DELAY_FASTEST); + + mSensorManager.registerListener(this, + mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), + SensorManager.SENSOR_DELAY_FASTEST); + + mSensorManager.registerListener(this, + mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), + SensorManager.SENSOR_DELAY_FASTEST); + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + } + + @Override + public void onSensorChanged(SensorEvent event) { + switch (event.sensor.getType()) { + case Sensor.TYPE_ACCELEROMETER: + // copy new accelerometer data into accel array and calculate orientation + System.arraycopy(event.values, 0, accel, 0, 3); + calculateAccMagOrientation(); + break; + + case Sensor.TYPE_GYROSCOPE: + // process gyro data + gyroFunction(event); + break; + + case Sensor.TYPE_MAGNETIC_FIELD: + // copy new magnetometer data into magnet array + System.arraycopy(event.values, 0, magnet, 0, 3); + break; + } + } + + // calculates orientation angles from accelerometer and magnetometer output + private void calculateAccMagOrientation() { + if (SensorManager.getRotationMatrix(rotationMatrix, null, accel, magnet)) { + SensorManager.getOrientation(rotationMatrix, accMagOrientation); + } + } + + // This function is borrowed from the Android reference + // at http://developer.android.com/reference/android/hardware/SensorEvent.html#values + // It calculates a rotation vector from the gyroscope angular speed values. + private void getRotationVectorFromGyro(float[] gyroValues, + float[] deltaRotationVector, + float timeFactor) { + float[] normValues = new float[3]; + + // Calculate the angular speed of the sample + float omegaMagnitude = + (float) Math.sqrt(gyroValues[0] * gyroValues[0] + + gyroValues[1] * gyroValues[1] + + gyroValues[2] * gyroValues[2]); + + // Normalize the rotation vector if it's big enough to get the axis + if (omegaMagnitude > EPSILON) { + normValues[0] = gyroValues[0] / omegaMagnitude; + normValues[1] = gyroValues[1] / omegaMagnitude; + normValues[2] = gyroValues[2] / omegaMagnitude; + } + + // Integrate around this axis with the angular speed by the timestep + // in order to get a delta rotation from this sample over the timestep + // We will convert this axis-angle representation of the delta rotation + // into a quaternion before turning it into the rotation matrix. + float thetaOverTwo = omegaMagnitude * timeFactor; + float sinThetaOverTwo = (float) Math.sin(thetaOverTwo); + float cosThetaOverTwo = (float) Math.cos(thetaOverTwo); + deltaRotationVector[0] = sinThetaOverTwo * normValues[0]; + deltaRotationVector[1] = sinThetaOverTwo * normValues[1]; + deltaRotationVector[2] = sinThetaOverTwo * normValues[2]; + deltaRotationVector[3] = cosThetaOverTwo; + } + + // This function performs the integration of the gyroscope data. + // It writes the gyroscope based orientation into gyroOrientation. + private void gyroFunction(SensorEvent event) { + // don't start until first accelerometer/magnetometer orientation has been acquired + if (accMagOrientation == null) + return; + + // initialisation of the gyroscope based rotation matrix + if (initState) { + float[] initMatrix = new float[9]; + initMatrix = getRotationMatrixFromOrientation(accMagOrientation); + float[] test = new float[3]; + SensorManager.getOrientation(initMatrix, test); + gyroMatrix = matrixMultiplication(gyroMatrix, initMatrix); + initState = false; + } + + // copy the new gyro values into the gyro array + // convert the raw gyro data into a rotation vector + float[] deltaVector = new float[4]; + if (timestamp != 0) { + final float dT = (event.timestamp - timestamp) * NS2S; + System.arraycopy(event.values, 0, gyro, 0, 3); + getRotationVectorFromGyro(gyro, deltaVector, dT / 2.0f); + } + + // measurement done, save current time for next interval + timestamp = event.timestamp; + + // convert rotation vector into rotation matrix + float[] deltaMatrix = new float[9]; + SensorManager.getRotationMatrixFromVector(deltaMatrix, deltaVector); + + // apply the new rotation interval on the gyroscope based rotation matrix + gyroMatrix = matrixMultiplication(gyroMatrix, deltaMatrix); + + // get the gyroscope based orientation from the rotation matrix + SensorManager.getOrientation(gyroMatrix, gyroOrientation); + } + + private float[] getRotationMatrixFromOrientation(float[] o) { + float[] xM = new float[9]; + float[] yM = new float[9]; + float[] zM = new float[9]; + + float sinX = (float) Math.sin(o[1]); + float cosX = (float) Math.cos(o[1]); + float sinY = (float) Math.sin(o[2]); + float cosY = (float) Math.cos(o[2]); + float sinZ = (float) Math.sin(o[0]); + float cosZ = (float) Math.cos(o[0]); + + // rotation about x-axis (pitch) + xM[0] = 1.0f; + xM[1] = 0.0f; + xM[2] = 0.0f; + xM[3] = 0.0f; + xM[4] = cosX; + xM[5] = sinX; + xM[6] = 0.0f; + xM[7] = -sinX; + xM[8] = cosX; + + // rotation about y-axis (roll) + yM[0] = cosY; + yM[1] = 0.0f; + yM[2] = sinY; + yM[3] = 0.0f; + yM[4] = 1.0f; + yM[5] = 0.0f; + yM[6] = -sinY; + yM[7] = 0.0f; + yM[8] = cosY; + + // rotation about z-axis (azimuth) + zM[0] = cosZ; + zM[1] = sinZ; + zM[2] = 0.0f; + zM[3] = -sinZ; + zM[4] = cosZ; + zM[5] = 0.0f; + zM[6] = 0.0f; + zM[7] = 0.0f; + zM[8] = 1.0f; + + // rotation order is y, x, z (roll, pitch, azimuth) + float[] resultMatrix = matrixMultiplication(xM, yM); + resultMatrix = matrixMultiplication(zM, resultMatrix); + return resultMatrix; + } + + private float[] matrixMultiplication(float[] A, float[] B) { + float[] result = new float[9]; + + result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6]; + result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7]; + result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8]; + + result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6]; + result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7]; + result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8]; + + result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6]; + result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7]; + result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8]; + + return result; + } + + class calculateFusedOrientationTask extends TimerTask { + public void run() { + float oneMinusCoeff = 1.0f - FILTER_COEFFICIENT; + + /* + * Fix for 179� <--> -179� transition problem: + * Check whether one of the two orientation angles (gyro or accMag) is negative while the other one is positive. + * If so, add 360� (2 * math.PI) to the negative value, perform the sensor fusion, and remove the 360� from the result + * if it is greater than 180�. This stabilizes the output in positive-to-negative-transition cases. + */ + + // azimuth + if (gyroOrientation[0] < -0.5 * Math.PI && accMagOrientation[0] > 0.0) { + fusedOrientation[0] = (float) (FILTER_COEFFICIENT * (gyroOrientation[0] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[0]); + fusedOrientation[0] -= (fusedOrientation[0] > Math.PI) ? 2.0 * Math.PI : 0; + } else if (accMagOrientation[0] < -0.5 * Math.PI && gyroOrientation[0] > 0.0) { + fusedOrientation[0] = (float) (FILTER_COEFFICIENT * gyroOrientation[0] + oneMinusCoeff * (accMagOrientation[0] + 2.0 * Math.PI)); + fusedOrientation[0] -= (fusedOrientation[0] > Math.PI) ? 2.0 * Math.PI : 0; + } else { + fusedOrientation[0] = FILTER_COEFFICIENT * gyroOrientation[0] + oneMinusCoeff * accMagOrientation[0]; + } + + // pitch + if (gyroOrientation[1] < -0.5 * Math.PI && accMagOrientation[1] > 0.0) { + fusedOrientation[1] = (float) (FILTER_COEFFICIENT * (gyroOrientation[1] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[1]); + fusedOrientation[1] -= (fusedOrientation[1] > Math.PI) ? 2.0 * Math.PI : 0; + } else if (accMagOrientation[1] < -0.5 * Math.PI && gyroOrientation[1] > 0.0) { + fusedOrientation[1] = (float) (FILTER_COEFFICIENT * gyroOrientation[1] + oneMinusCoeff * (accMagOrientation[1] + 2.0 * Math.PI)); + fusedOrientation[1] -= (fusedOrientation[1] > Math.PI) ? 2.0 * Math.PI : 0; + } else { + fusedOrientation[1] = FILTER_COEFFICIENT * gyroOrientation[1] + oneMinusCoeff * accMagOrientation[1]; + } + + // roll + if (gyroOrientation[2] < -0.5 * Math.PI && accMagOrientation[2] > 0.0) { + fusedOrientation[2] = (float) (FILTER_COEFFICIENT * (gyroOrientation[2] + 2.0 * Math.PI) + oneMinusCoeff * accMagOrientation[2]); + fusedOrientation[2] -= (fusedOrientation[2] > Math.PI) ? 2.0 * Math.PI : 0; + } else if (accMagOrientation[2] < -0.5 * Math.PI && gyroOrientation[2] > 0.0) { + fusedOrientation[2] = (float) (FILTER_COEFFICIENT * gyroOrientation[2] + oneMinusCoeff * (accMagOrientation[2] + 2.0 * Math.PI)); + fusedOrientation[2] -= (fusedOrientation[2] > Math.PI) ? 2.0 * Math.PI : 0; + } else { + fusedOrientation[2] = FILTER_COEFFICIENT * gyroOrientation[2] + oneMinusCoeff * accMagOrientation[2]; + } + + // overwrite gyro matrix and orientation with fused orientation + // to comensate gyro drift + gyroMatrix = getRotationMatrixFromOrientation(fusedOrientation); + System.arraycopy(fusedOrientation, 0, gyroOrientation, 0, 3); + } + } +} diff --git a/app/src/main/res/drawable-hdpi/ic_stat_name.png b/app/src/main/res/drawable-hdpi/ic_stat_name.png new file mode 100644 index 0000000..f952cc5 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_name.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_stat_name.png b/app/src/main/res/drawable-mdpi/ic_stat_name.png new file mode 100644 index 0000000..5a26a7a Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_stat_name.png differ diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..1f6bb29 --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_name.png b/app/src/main/res/drawable-xhdpi/ic_stat_name.png new file mode 100644 index 0000000..151bb39 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_name.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_stat_name.png b/app/src/main/res/drawable-xxhdpi/ic_stat_name.png new file mode 100644 index 0000000..d386e54 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_stat_name.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_stat_name.png b/app/src/main/res/drawable-xxxhdpi/ic_stat_name.png new file mode 100644 index 0000000..e96dda4 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_stat_name.png differ diff --git a/app/src/main/res/drawable/active_button.xml b/app/src/main/res/drawable/active_button.xml new file mode 100644 index 0000000..a20106e --- /dev/null +++ b/app/src/main/res/drawable/active_button.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/databurn_logo.png b/app/src/main/res/drawable/databurn_logo.png new file mode 100644 index 0000000..129a3ff Binary files /dev/null and b/app/src/main/res/drawable/databurn_logo.png differ diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..0d025f9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/privacy_breacher.png b/app/src/main/res/drawable/privacy_breacher.png new file mode 100644 index 0000000..4e7e1a9 Binary files /dev/null and b/app/src/main/res/drawable/privacy_breacher.png differ diff --git a/app/src/main/res/layout/activity_about.xml b/app/src/main/res/layout/activity_about.xml new file mode 100644 index 0000000..7487a24 --- /dev/null +++ b/app/src/main/res/layout/activity_about.xml @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..b853218 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + +