├── settings.gradle
├── .dockerignore
├── .idea
├── .gitignore
├── compiler.xml
├── vcs.xml
├── misc.xml
└── jarRepositories.xml
├── .yamllint
├── app
├── libs
│ └── protobuf-java-3.6.0.jar
├── src
│ └── main
│ │ ├── ic_launcher-web.png
│ │ ├── jniLibs
│ │ ├── x86
│ │ │ └── libhu_jni.so
│ │ └── armeabi
│ │ │ └── libhu_jni.so
│ │ ├── res
│ │ ├── drawable
│ │ │ ├── aawifi.png
│ │ │ ├── hu_icon_256.png
│ │ │ └── ic_launcher_background.xml
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_launcher_round.png
│ │ │ └── ic_launcher_foreground.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_launcher_round.png
│ │ │ └── ic_launcher_foreground.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_launcher_round.png
│ │ │ └── ic_launcher_foreground.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_launcher_round.png
│ │ │ └── ic_launcher_foreground.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_launcher_round.png
│ │ │ └── ic_launcher_foreground.png
│ │ ├── values
│ │ │ ├── white.xml
│ │ │ ├── colors.xml
│ │ │ ├── styles.xml
│ │ │ └── strings.xml
│ │ ├── xml
│ │ │ └── accessory_filter.xml
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ └── layout
│ │ │ └── activity_main.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── north3221
│ │ └── aagateway
│ │ ├── AAlogger.java
│ │ ├── MainActivity.java
│ │ ├── HackerService.java
│ │ └── ConnectionStateReceiver.java
├── proguard-rules.pro
└── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── Dockerfile
├── .gitignore
├── .github
└── workflows
│ └── build-apk.yml
├── gradlew.bat
├── README.md
└── gradlew
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | .git
2 | app/build
3 | build
4 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.yamllint:
--------------------------------------------------------------------------------
1 | ---
2 | extends: default
3 |
4 | rules:
5 | line-length: disable
6 | truthy: disable
7 |
--------------------------------------------------------------------------------
/app/libs/protobuf-java-3.6.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/libs/protobuf-java-3.6.0.jar
--------------------------------------------------------------------------------
/app/src/main/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/ic_launcher-web.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/jniLibs/x86/libhu_jni.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/jniLibs/x86/libhu_jni.so
--------------------------------------------------------------------------------
/app/src/main/res/drawable/aawifi.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/drawable/aawifi.png
--------------------------------------------------------------------------------
/app/src/main/jniLibs/armeabi/libhu_jni.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/jniLibs/armeabi/libhu_jni.so
--------------------------------------------------------------------------------
/app/src/main/res/drawable/hu_icon_256.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/drawable/hu_icon_256.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values/white.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFFFFF
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/north3221/AAGateWayWiFi/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/accessory_filter.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AAGateWay
3 | Will starts the AAWireless Hacker Service when AA USB Adapter is connected and WiFi is connected
4 | Exit
5 | Logging level: Set the logging level
6 | Control WiFi: Turn Wifi on/off with power
7 | Alternative usb toggle
8 | Request Battery
9 | Request Root
10 | Request Storage
11 |
12 | - off
13 | - info
14 | - full
15 | - full + log
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:20.04
2 |
3 | ENV DEBIAN_FRONTEND=noninteractive
4 |
5 | # https://developer.android.com/studio/index.html#command-tools
6 |
7 | WORKDIR /opt/android
8 |
9 | RUN apt-get update \
10 | && apt-get install -y \
11 | curl \
12 | unzip \
13 | openjdk-8-jdk
14 |
15 | # jdk 8, 11, 13 ,16
16 | # && apt-get install -y android-sdk
17 |
18 | ENV ANDROID_HOME=/opt/android
19 | ENV PATH=$ANDROID_HOME/cmdline-tools/tools/bin/:$PATH
20 | ENV PATH=$ANDROID_HOME/emulator/:$PATH
21 | ENV PATH=$ANDROID_HOME/platform-tools/:$PATH
22 |
23 | RUN curl -L $(curl -sL https://developer.android.com/studio/index.html\#command-tools | grep "zip" | grep "linux" | grep "commandline" | grep "href" | cut -d'"' -f2) -O \
24 | && unzip $(ls | grep zip) \
25 | && rm -rf $(ls | grep zip) \
26 | && mkdir tools \
27 | && mv cmdline-tools/* tools \
28 | && mv tools cmdline-tools/ \
29 | && yes | sdkmanager --licenses
30 |
31 | # ENV GRADLE_OPTS=-Djava.io.tmpdir=/repo/
32 | # export GRADLE_OPTS=-Djava.io.tmpdir=/repo/
33 |
34 | # ./gradlew assemble
35 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 |
4 | android {
5 | compileSdkVersion 27
6 | defaultConfig {
7 | applicationId "com.north3221.aagateway"
8 | minSdkVersion 14
9 | //noinspection ExpiredTargetSdkVersion
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0.3 Alpha"
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 | multiDexEnabled true
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | }
23 |
24 | dependencies {
25 | implementation fileTree(include: ['*.jar'], dir: 'libs')
26 | implementation 'com.android.support:appcompat-v7:27.1.1+'
27 | implementation 'com.android.support.constraint:constraint-layout:1.0.2'
28 | testImplementation 'junit:junit:4.12'
29 | androidTestImplementation 'com.android.support.test:runner:1.0.1'
30 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
31 | implementation files('libs/protobuf-java-3.6.0.jar')
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # IDE
2 | *.iml
3 | app/*.iml
4 |
5 | # Built application files
6 | *.apk
7 | *.ap_
8 |
9 | # Files for the ART/Dalvik VM
10 | *.dex
11 |
12 | # Java class files
13 | *.class
14 |
15 | # Generated files
16 | bin/
17 | gen/
18 | out/
19 |
20 | # Gradle files
21 | .gradle/
22 | build/
23 |
24 | # Local configuration file (sdk path, etc)
25 | local.properties
26 |
27 | # Proguard folder generated by Eclipse
28 | proguard/
29 |
30 | # Log Files
31 | *.log
32 |
33 | # Android Studio Navigation editor temp files
34 | .navigation/
35 |
36 | # Android Studio captures folder
37 | captures/
38 |
39 | # IntelliJ
40 | *.iml
41 | .idea/workspace.xml
42 | .idea/tasks.xml
43 | .idea/gradle.xml
44 | .idea/assetWizardSettings.xml
45 | .idea/dictionaries
46 | .idea/libraries
47 | .idea/caches
48 |
49 | # Keystore files
50 | # Uncomment the following line if you do not want to check your keystore files in.
51 | #*.jks
52 |
53 | # External native build folder generated in Android Studio 2.2 and later
54 | .externalNativeBuild
55 |
56 | # Google Services (e.g. APIs or Firebase)
57 | google-services.json
58 |
59 | # Freeline
60 | freeline.py
61 | freeline/
62 | freeline_project_description.json
63 |
64 | # fastlane
65 | fastlane/report.xml
66 | fastlane/Preview.html
67 | fastlane/screenshots
68 | fastlane/test_output
69 | fastlane/readme.md
70 |
--------------------------------------------------------------------------------
/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/.github/workflows/build-apk.yml:
--------------------------------------------------------------------------------
1 | ---
2 | name: Build APK
3 |
4 | on:
5 | push:
6 | branches:
7 | - master
8 | tags:
9 | - v*
10 | pull_request:
11 | branches:
12 | - master
13 |
14 | jobs:
15 | tests:
16 | runs-on: ubuntu-latest
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: "YamlLint"
20 | run: |
21 | docker run \
22 | --rm \
23 | -w /repo \
24 | -v $(pwd):/repo \
25 | -t \
26 | alpine:3.13 /bin/sh -c " \
27 | apk add --no-cache py-pip python3 bash \
28 | && pip3 install yamllint \
29 | && yamllint -s . \
30 | "
31 | - name: "ShellCheck"
32 | run: |
33 | docker run \
34 | --rm \
35 | -w /repo \
36 | -v $(pwd):/repo \
37 | -t \
38 | alpine:3.13 /bin/sh -c " \
39 | apk add --no-cache shellcheck bash \
40 | && shellcheck $(find . -type f -name "*.sh" | tr '\n' ' ')
41 | "
42 | build:
43 | runs-on: ubuntu-latest
44 | steps:
45 | - uses: actions/checkout@v2
46 | - name: "Build APK"
47 | run: ./build_in_docker.sh
48 | - name: Release
49 | uses: softprops/action-gh-release@v1
50 | if: startsWith(github.ref, 'refs/tags/')
51 | with:
52 | tag_name: ${{ github.ref }}
53 | name: Release ${{ github.ref }}
54 | draft: true
55 | files: |
56 | ./app/build/outputs/apk/debug/*
57 | env:
58 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # You don't need to add this in secrets it's by default.
59 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS="-Xmx64m"
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AAGateWay Wireless Android Auto using Master Wifi Hotspot (Root required on slave)
2 |
3 | I have reworked the AAGateway to wait for USB adapter AND connection to WiFi.
4 | This only works running on the slave and connecting to master wifi hotspot
5 |
6 | Shout out to the (couldn't of done this without them):
7 | * The original [AAGateWay](https://github.com/borconi/AAGateWay)
8 | * Also the modified [AAGateWay](https://github.com/olivluca/AAGateWay)
9 |
10 | [XDA forum link](https://forum.xda-developers.com/t/android-4-1-proxy-gateway-for-android-auto.3813163) for discussion, requests and support
11 |
12 | You can build it or get it from the [Releases](https://github.com/north3221/AAGateWayWiFi/releases) section and you have to install it on the slave phone.
13 |
14 | ## Set up:
15 | ### MASTER (doesn't need to be rooted)
16 | * You MUST have [Android Auto Head Unit Server running](https://developer.android.com/training/cars/testing#:~:text=You%20only%20need%20to%20enable,server%20(see%20figure%201).) on your Master device (you cna just leave it running)
17 | * You also must have WifI tether on Master device, which the slave can connect to
18 | NB I use Tasker to automate both of these things i.e. turn on wifi tether when connected to car bluetooth and some screen touches for AA HUS
19 |
20 | ### SLAVE
21 | * Remove battery restrictions on AAgateway app on slave - Click the request battery button
22 | * Allow storage access - Click the request storage button This is for writing a log file to sdcard when logging set to full + log
23 | * Root is required - click request root button. This is to enable toggling USB to connect to car head unit when service ready
24 | * Ensure slave can connect to master wifi tether, i.e. save the network. But NO other wifi (you don't want it to connect to the wrong network)
25 | * Worth making sure that the screen wakes on power input, as some phones don't connect to wifi with screen off. This app does wake lock for up to 5 mins but doesnt work if screen off
26 |
27 | #### Settings
28 | * Logging Level: Prob worth changing it to full + log while setting up (shows stuff in ui and writes to sdcard/aagatewaylog.txt)
29 | Full just shows it all in ui (ui only updates when app is open), and info just shows the key elements on screen.
30 | * The setting control wifi means the app will turn on wifi when the slave is powered and turn it off after its has no power.
31 | The app only waits for wifi connection, not specifically your master, hence make sure only one wifi set up
32 | * Alternative usb toggle is if the standard one doesn't work (see later)
33 |
34 | ~~First time you try connecting you will need to allowed root access (TODO add prompt at startup)~~ done
35 | First time it will prompt do you want to use aawireless for android automotive, click 'always'
36 |
37 | Once done, plug slave into car, turn car on, enable wifi (if set wifi control to true, does it for you)
38 | Slave should show it has usb device and once connects to master wifi, then wifi will show connected, then usb will toggle and service will start
39 |
40 | AA should fire up, if not it will retry. Let it retry a few times
41 | If it doesn't work, unplug slave and restart your HUS on master (i.e. stop it and start it again). Then try again
42 |
43 | If after a few attempts of this you never get a flash of Android Auto then possibly there is issue between head unit, slave and master.
44 | I've put in an alternate usb toggle option. So change that setting to true and try it all again.
45 | If still fails after that then no idea, sorry. If you can debug it yourself great, raise a pr
46 |
47 | NB I an NOT a developer, just a hobbyist who likes to play and would like AA wireless in his car :-)
48 | I only have a couple of combinations to try and test this on. Happy to look at issues but be patient I may never get to em, my focus is it working for me, just sharing to try and help others.
49 | Please don't start complaining if its not working or I am not responsive to questions or issues
50 |
51 |
52 | #### Known issues
53 |
54 | ~~If slave stops, master doesn't seem to realise (AA still thinks its connected). This bawks the HUS. So you need to restart the HUS before next use
55 | TODO find a more graceful way of killing connection~~ DONE
56 |
57 |
58 | Many other issues... this wont be plane sailing, so dont expect it to be!!
--------------------------------------------------------------------------------
/app/src/main/java/com/north3221/aagateway/AAlogger.java:
--------------------------------------------------------------------------------
1 | package com.north3221.aagateway;
2 |
3 | import static com.north3221.aagateway.MainActivity.SHARED_PREF_NAME;
4 | import static com.north3221.aagateway.MainActivity.TAG;
5 |
6 | import android.content.Context;
7 | import android.content.SharedPreferences;
8 | import android.os.Build;
9 | import android.support.annotation.RequiresApi;
10 | import android.util.Log;
11 | import java.io.BufferedWriter;
12 | import java.io.File;
13 | import java.io.FileWriter;
14 | import java.io.IOException;
15 | import java.text.SimpleDateFormat;
16 |
17 | class AAlogger {
18 | public static final String
19 | SHARED_PREF_KEY_LOG = "LOG",
20 | LOGFILE = "sdcard/aagatewaylog.txt";
21 | private final Context loggerContext;
22 |
23 | public AAlogger(Context context){
24 | loggerContext = context;
25 | }
26 |
27 | public void log(String message, String tvName){
28 | switch (loggingLevel()){
29 | case 0:
30 | break;
31 | case 3:
32 | log(message);
33 | case 2:
34 | if (!tvName.equals("log")){
35 | updateTextView(message, "log");
36 | }
37 | case 1:
38 | if (tvName.equals("log") && loggingLevel() == 1){
39 | break;
40 | }
41 | updateTextView(message,tvName);
42 | break;
43 | }
44 |
45 | }
46 |
47 | public void log(String message){
48 | if (loggingLevel() > 2 && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
49 | appendLog(message);
50 | }
51 |
52 | private void updateTextView(String message, String tvName){
53 |
54 | int id = loggerContext.getResources().getIdentifier(tvName, "id", loggerContext.getPackageName());
55 | Log.d(TAG, "Updating Shared Preferences for tvName:= " + tvName + " ID:= " + id);
56 | SharedPreferences sp = loggerContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
57 | if (tvName.equals("log")) {
58 | String timeStamp = new SimpleDateFormat("HH:mm:ss").format(new java.util.Date());
59 | message = timeStamp + ":" + message + "\n" + sp.getString(String.valueOf(id), "");
60 | }
61 | if (message.length() > 5120){
62 | message = message.substring(0, 5120);
63 | }
64 | SharedPreferences.Editor spEditor = sp.edit();
65 | spEditor.putString(String.valueOf(id), message);
66 | spEditor.apply();
67 | }
68 |
69 |
70 | private int loggingLevel(){
71 | SharedPreferences sharedpreferences = loggerContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
72 | return sharedpreferences.getInt(SHARED_PREF_KEY_LOG,0);
73 |
74 | }
75 |
76 | @RequiresApi(api = Build.VERSION_CODES.KITKAT)
77 | private void appendLog(String text)
78 | {
79 | File logFile = new File(LOGFILE);
80 | if (logFile.exists() && logFile.length() > 50000){
81 | logFile.delete();
82 | }
83 | if (!logFile.exists())
84 | {
85 | try {
86 | logFile.createNewFile();
87 | }
88 | catch (IOException e) {
89 | // TODO Auto-generated catch block
90 | e.printStackTrace();
91 | }
92 | }
93 | String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH:mm:ss").format(new java.util.Date());
94 | try (BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true))) {
95 | buf.append(timeStamp).append(": ").append(text);
96 | buf.newLine();
97 | } catch (IOException e) {
98 | // TODO Auto-generated catch block
99 | e.printStackTrace();
100 | }
101 | }
102 |
103 | public void loggingLevelChanged(){
104 | switch (loggingLevel()){
105 | case 0:
106 | removeSharedPref("usbconnection");
107 | removeSharedPref("wificonnection");
108 | removeSharedPref("aaservice");
109 | case 1:
110 | removeSharedPref("log");
111 | case 2:
112 | deleteLogfile();
113 | }
114 | }
115 |
116 | private void deleteLogfile(){
117 | Log.d(TAG, "Deleting Log File");
118 | File logFile = new File(LOGFILE);
119 | logFile.delete();
120 |
121 | }
122 |
123 | private void removeSharedPref(String name){
124 | String id = String.valueOf(loggerContext.getResources().getIdentifier(name, "id", loggerContext.getPackageName()));
125 | Log.d(TAG, "Removing Shared Preferences for tvName:= " + name);
126 | SharedPreferences sp = loggerContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
127 | SharedPreferences.Editor spEditor = sp.edit();
128 | spEditor.putString(id,"");
129 | spEditor.apply();
130 | spEditor.remove(id);
131 | spEditor.apply();
132 |
133 | }
134 |
135 | }
136 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
20 |
21 |
27 |
28 |
34 |
40 |
41 |
47 |
48 |
55 |
56 |
61 |
62 |
63 |
68 |
69 |
77 |
78 |
84 |
85 |
93 |
94 |
95 |
96 |
103 |
104 |
105 |
106 |
113 |
114 |
123 |
132 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS='"-Xmx64m"'
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/com/north3221/aagateway/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.north3221.aagateway;
2 |
3 |
4 | import static com.north3221.aagateway.AAlogger.SHARED_PREF_KEY_LOG;
5 | import static com.north3221.aagateway.ConnectionStateReceiver.ACTION_USB_ACCESSORY_ATTACHED;
6 | import static com.north3221.aagateway.ConnectionStateReceiver.ACTION_USB_ACCESSORY_DETACHED;
7 | import static com.north3221.aagateway.ConnectionStateReceiver.SHARED_PREF_KEY_USB_CONTROL_TYPE;
8 | import static com.north3221.aagateway.ConnectionStateReceiver.SHARED_PREF_KEY_WIFI_CONTROL;
9 |
10 | import android.Manifest;
11 | import android.content.ComponentName;
12 | import android.content.Context;
13 | import android.content.Intent;
14 | import android.content.SharedPreferences;
15 | import android.content.pm.PackageManager;
16 | import android.hardware.usb.UsbManager;
17 | import android.net.Uri;
18 | import android.os.Build;
19 | import android.os.Bundle;
20 | import android.os.PowerManager;
21 | import android.provider.Settings;
22 | import android.support.v4.app.ActivityCompat;
23 | import android.support.v4.content.ContextCompat;
24 | import android.support.v7.app.AppCompatActivity;
25 | import android.support.v7.widget.AppCompatTextView;
26 | import android.util.Log;
27 | import android.view.View;
28 | import android.view.ViewGroup;
29 | import android.widget.AdapterView;
30 | import android.widget.ArrayAdapter;
31 | import android.widget.Button;
32 | import android.widget.CompoundButton;
33 | import android.widget.LinearLayout;
34 | import android.widget.Spinner;
35 | import android.widget.Switch;
36 | import android.widget.TextView;
37 | import android.widget.Toast;
38 |
39 | import java.io.BufferedReader;
40 | import java.io.IOException;
41 | import java.io.InputStreamReader;
42 | import java.util.Arrays;
43 |
44 |
45 | public class MainActivity extends AppCompatActivity {
46 |
47 | public static final String
48 | TAG = "AAGateWay",
49 | SHARED_PREF_NAME = TAG,
50 | SHARED_PREF_KEY_ROOT = "HAS_ROOT";
51 | private static final int STORAGE_PERMISSION_REQUEST_CODE = 0;
52 |
53 | private static SharedPreferences sharedpreferences;
54 | private AAlogger aalogger;
55 |
56 |
57 | @Override
58 | protected void onCreate(Bundle savedInstanceState) {
59 | super.onCreate(savedInstanceState);
60 | setContentView(R.layout.activity_main);
61 | aalogger = new AAlogger(this);
62 |
63 | sharedpreferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
64 | checkBatteryOptimised();
65 | checkRoot();
66 | checkExternalStorage();
67 |
68 | Button button = findViewById(R.id.exitButton);
69 | button.setOnClickListener(new View.OnClickListener() {
70 | @Override
71 | public void onClick(View view) {
72 | finish();
73 | }
74 | });
75 | createLoggingSpinner();
76 | createWiFiSwitch();
77 | createUsbSwitch();
78 |
79 | }
80 |
81 | @Override
82 | protected void onResume() {
83 | super.onResume();
84 | updateAllTextViews();
85 | sharedpreferences.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
86 | }
87 |
88 | @Override
89 | protected void onPause() {
90 | super.onPause();
91 | sharedpreferences.unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
92 | }
93 |
94 | @Override
95 | protected void onNewIntent(Intent paramIntent) {
96 | Log.i(TAG, "Got new intent: " + paramIntent);
97 | Intent usbIntent;
98 | if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(paramIntent.getAction()) && paramIntent.hasExtra(UsbManager.EXTRA_ACCESSORY)){
99 | usbIntent = new Intent(ACTION_USB_ACCESSORY_ATTACHED);
100 | ComponentName componentName = new ComponentName(this,ConnectionStateReceiver.class);
101 | usbIntent.setComponent(componentName);
102 | usbIntent.putExtra(UsbManager.EXTRA_ACCESSORY, paramIntent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY));
103 | } else {
104 | usbIntent = new Intent(ACTION_USB_ACCESSORY_DETACHED);
105 | }
106 | sendBroadcast(usbIntent);
107 | }
108 |
109 | private void createLoggingSpinner(){
110 | final Spinner spinnerLogging = findViewById(R.id.logging);
111 | ArrayAdapter adapter=ArrayAdapter.createFromResource(this, R.array.logging, android.R.layout.simple_spinner_item);
112 | adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
113 | spinnerLogging.setAdapter(adapter);
114 |
115 | spinnerLogging.setSelection(sharedpreferences.getInt(SHARED_PREF_KEY_LOG,0));
116 |
117 | spinnerLogging.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
118 | @Override
119 | public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
120 | SharedPreferences.Editor editor = sharedpreferences.edit();
121 | editor.putInt(SHARED_PREF_KEY_LOG, spinnerLogging.getSelectedItemPosition());
122 | editor.apply();
123 | Log.d(TAG,"Logging level changed:= "+i);
124 |
125 | aalogger.loggingLevelChanged();
126 |
127 | }
128 |
129 | @Override
130 | public void onNothingSelected(AdapterView> adapterView) {
131 |
132 | }
133 | });
134 | }
135 |
136 | private void createWiFiSwitch(){
137 | final Switch swWiFiCtrl = findViewById(R.id.wificontrol);
138 | swWiFiCtrl.setChecked(sharedpreferences.getBoolean(SHARED_PREF_KEY_WIFI_CONTROL,true));
139 | swWiFiCtrl.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
140 |
141 | @Override
142 | public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
143 | SharedPreferences.Editor editor = sharedpreferences.edit();
144 | editor.putBoolean(SHARED_PREF_KEY_WIFI_CONTROL,b);
145 | editor.apply();
146 | }
147 | });
148 |
149 | }
150 |
151 | private void createUsbSwitch(){
152 | final Switch swUsbCtrl = findViewById(R.id.alternateusbtoggle);
153 | swUsbCtrl.setChecked(sharedpreferences.getBoolean(SHARED_PREF_KEY_USB_CONTROL_TYPE,false));
154 | swUsbCtrl.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
155 |
156 | @Override
157 | public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
158 | SharedPreferences.Editor editor = sharedpreferences.edit();
159 | editor.putBoolean(SHARED_PREF_KEY_USB_CONTROL_TYPE,b);
160 | editor.apply();
161 | }
162 | });
163 |
164 | }
165 |
166 | private void checkBatteryOptimised(){
167 | if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
168 | PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
169 | if (pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName())) {
170 | findViewById(R.id.requestGroup).setVisibility(View.VISIBLE);
171 | final Button batteryButton = findViewById(R.id.requestBattery);
172 | batteryButton.setVisibility(View.VISIBLE);
173 | batteryButton.setOnClickListener(new View.OnClickListener() {
174 | @Override
175 | public void onClick(View view) {
176 | Intent intent = new Intent();
177 | intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
178 | intent.setData(Uri.parse("package:" + getPackageName()));
179 | startActivity(intent);
180 | batteryButton.setVisibility(View.INVISIBLE);
181 | }
182 | });
183 | }
184 | }
185 | }
186 |
187 | private void checkRoot(){
188 | if (sharedpreferences.getBoolean(SHARED_PREF_KEY_ROOT,false))
189 | return;
190 |
191 | findViewById(R.id.requestGroup).setVisibility(View.VISIBLE);
192 | final Button rootButton = findViewById(R.id.requestRoot);
193 | rootButton.setVisibility(View.VISIBLE);
194 | rootButton.setOnClickListener(new View.OnClickListener() {
195 | @Override
196 | public void onClick(View view) {
197 | requestRoot();
198 | finish();
199 | startActivity(getIntent());
200 | }
201 | });
202 | }
203 |
204 | private void requestRoot(){
205 | try {
206 | String [] cmdTestSU = new String[]{"su", "-c", "ls", "/"};
207 | Process p = Runtime.getRuntime().exec(cmdTestSU);
208 | BufferedReader bufferedReader = new BufferedReader(
209 | new InputStreamReader(p.getInputStream()));
210 |
211 | // Grab the results
212 | StringBuilder resRoot = new StringBuilder();
213 | String line;
214 | while ((line = bufferedReader.readLine()) != null) {
215 | resRoot.append(line).append("\n");
216 | }
217 | if (resRoot.length()>0) {
218 | SharedPreferences.Editor editor = sharedpreferences.edit();
219 | editor.putBoolean(SHARED_PREF_KEY_ROOT, true);
220 | editor.apply();
221 | }
222 |
223 | } catch (IOException e) {
224 | e.printStackTrace();
225 | Log.e(TAG,"Error getting root:", e);
226 | }
227 | }
228 |
229 | private void checkExternalStorage(){
230 | if (ContextCompat.checkSelfPermission(this,
231 | Manifest.permission.WRITE_EXTERNAL_STORAGE)
232 | != PackageManager.PERMISSION_GRANTED) {
233 | findViewById(R.id.requestGroup).setVisibility(View.VISIBLE);
234 | final Button storageButton = findViewById(R.id.requestStorage);
235 | storageButton.setVisibility(View.VISIBLE);
236 | storageButton.setOnClickListener(new View.OnClickListener() {
237 | @Override
238 | public void onClick(View view) {
239 | requestStorage();
240 | }
241 | });
242 | }
243 | }
244 |
245 | private void requestStorage(){
246 | ActivityCompat.requestPermissions(this,
247 | new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0);
248 | }
249 |
250 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
251 | if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
252 | // If request is cancelled, the result arrays are empty.
253 | if (grantResults.length > 0
254 | && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
255 | finish();
256 | startActivity(getIntent());
257 | } else {
258 | Toast.makeText(this,"Unknown permission:= " + Arrays.toString(grantResults),Toast.LENGTH_SHORT).show();
259 | aalogger.log("Unknown permission:= " + Arrays.toString(grantResults));
260 | }
261 |
262 | }
263 | }
264 |
265 | private final SharedPreferences.OnSharedPreferenceChangeListener onSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
266 |
267 | @Override
268 | public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
269 | try{
270 | int id = Integer.parseInt(key);
271 | Log.d(TAG, "updating text view id:= " + id);
272 | if (findViewById(id) instanceof TextView) {
273 | updateTextView((TextView) findViewById(id));
274 | }
275 | } catch (NumberFormatException e) {
276 | Log.d(TAG, "None Automated Shared Preferences update Key:= " + key);
277 | }
278 |
279 | }
280 | };
281 |
282 |
283 | private void updateTextView(TextView tv){
284 | tv.setText(sharedpreferences.getString(String.valueOf(tv.getId()), (String) tv.getText()));
285 | }
286 |
287 | private void updateAllTextViews(){
288 | LinearLayout maLayout = findViewById(R.id.main_activity);
289 | for (int i = 0; i < maLayout.getChildCount(); ++i){
290 | View v = maLayout.getChildAt(i);
291 | if (v instanceof ViewGroup){
292 | ViewGroup vg = (ViewGroup) v;
293 | for (int j = 0;j < vg.getChildCount(); j++){
294 | View cv = vg.getChildAt(j);
295 | if (cv instanceof AppCompatTextView){
296 | updateTextView((TextView) cv);
297 | }
298 | }
299 | } else {
300 | if (v instanceof AppCompatTextView) {
301 | updateTextView((TextView) v);
302 | }
303 | }
304 | }
305 |
306 | }
307 |
308 | }
309 |
--------------------------------------------------------------------------------
/app/src/main/java/com/north3221/aagateway/HackerService.java:
--------------------------------------------------------------------------------
1 | package com.north3221.aagateway;
2 |
3 | import android.app.Notification;
4 | import android.app.NotificationChannel;
5 | import android.app.NotificationManager;
6 | import android.app.Service;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.graphics.Color;
10 | import android.hardware.usb.UsbAccessory;
11 | import android.hardware.usb.UsbManager;
12 | import android.os.Binder;
13 | import android.os.Build;
14 | import android.os.IBinder;
15 | import android.os.Looper;
16 | import android.os.ParcelFileDescriptor;
17 | import android.support.annotation.RequiresApi;
18 | import android.util.Log;
19 | import java.io.DataInputStream;
20 | import java.io.FileDescriptor;
21 | import java.io.FileInputStream;
22 | import java.io.FileOutputStream;
23 | import java.io.IOException;
24 | import java.io.OutputStream;
25 | import java.net.Socket;
26 | import java.net.InetAddress;
27 | import java.net.InetSocketAddress;
28 | import java.util.Arrays;
29 |
30 |
31 |
32 | import static android.app.NotificationManager.IMPORTANCE_HIGH;
33 | import static com.north3221.aagateway.ConnectionStateReceiver.ACTION_RESET_AASERVICE;
34 | import static java.lang.Thread.sleep;
35 |
36 | public class HackerService extends Service {
37 | private static final String TAG = "AAGateWay";
38 | private NotificationManager mNotificationManager;
39 | private final IBinder mBinder = new LocalBinder();
40 | private String gatewayIP;
41 | private ParcelFileDescriptor mFileDescriptor;
42 | private FileOutputStream phoneOutputStream;
43 | private FileInputStream phoneInputStream;
44 | private AAlogger logger;
45 | private static final String tvName = "aaservice";
46 |
47 | private static Socket phoneTcpSocket;
48 | private static OutputStream socketoutput;
49 | private static DataInputStream socketinput;
50 | public static boolean running=false;
51 | private boolean localCompleted,usbCompleted;
52 | byte [] readbuffer = new byte[16384];
53 |
54 | @Override
55 | public IBinder onBind(Intent intent) {
56 | return mBinder;
57 | }
58 | public class LocalBinder extends Binder {
59 | HackerService getService() {
60 | return HackerService.this;
61 | }
62 | }
63 |
64 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
65 | @Override
66 | public void onCreate() {
67 | super.onCreate();
68 | logger = new AAlogger(getApplicationContext());
69 |
70 | String CHANNEL_ONE_ID = "com.north3221.aagateway";
71 | String CHANNEL_ONE_NAME = "Channel One";
72 | NotificationChannel notificationChannel;
73 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
74 | notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
75 | CHANNEL_ONE_NAME, IMPORTANCE_HIGH);
76 | notificationChannel.enableLights(true);
77 | notificationChannel.setLightColor(Color.RED);
78 | notificationChannel.setShowBadge(true);
79 | notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
80 | NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
81 | if (manager != null) {
82 | manager.createNotificationChannel(notificationChannel);
83 | }
84 | }
85 |
86 |
87 | mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
88 | Notification.Builder mynotification = new Notification.Builder(this)
89 | .setContentTitle("Android Auto GateWay")
90 | .setContentText("Running....")
91 | .setSmallIcon(R.drawable.aawifi)
92 | .setTicker("");
93 | if (Build.VERSION.SDK_INT>=26)
94 | mynotification.setChannelId(CHANNEL_ONE_ID);
95 |
96 | startForeground(1, mynotification.build());
97 |
98 | }
99 |
100 | @Override
101 | public int onStartCommand(Intent intent, int flags, int startId) {
102 |
103 | if (running) {
104 | Log.d(TAG,"Service already running");
105 | logger.log("Already Running", tvName);
106 | return START_STICKY;
107 | }
108 | Log.d(TAG,"Service Started");
109 | logger.log("Started",tvName);
110 | super.onStartCommand(intent, flags, startId);
111 | UsbAccessory mAccessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
112 | gatewayIP = intent.getStringExtra("gwip");
113 | UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
114 | if (mUsbManager != null) {
115 | mFileDescriptor = mUsbManager.openAccessory(mAccessory);
116 | }
117 | if (mFileDescriptor != null) {
118 | FileDescriptor fd = mFileDescriptor.getFileDescriptor();
119 | phoneInputStream = new FileInputStream(fd);
120 | phoneOutputStream = new FileOutputStream(fd);
121 | usbCompleted=false;
122 | } else {
123 | Log.e(TAG, "Cannot open usb accessory "+ mAccessory.toString());
124 | stopSelf();
125 | return START_STICKY;
126 | }
127 |
128 | //Manually start AA.
129 | logger.log("Running",tvName);
130 | running=true;
131 | localCompleted = false;
132 | usbCompleted = false;
133 | Thread usbreader = new Thread(new usbpollthread());
134 | Thread tcpreader = new Thread(new tcppollthread());
135 | usbreader.start();
136 | tcpreader.start();
137 |
138 | return START_STICKY;
139 | }
140 |
141 | class tcppollthread implements Runnable {
142 | public void run() {
143 | Looper.prepare();
144 | Log.d(TAG,"tcp - run");
145 | logger.log("TCP polling thread started - running:= " + running, "log");
146 |
147 | try {
148 | logger.log("Connecting to phone: " + gatewayIP, tvName);
149 | InetAddress addr = InetAddress.getByName(gatewayIP);
150 |
151 | if (addr.isReachable(300)) {
152 | Log.d(TAG, "tcp - reachable " + gatewayIP);
153 | } else {
154 | Log.d(TAG, "tcp - not reachable " + gatewayIP);
155 | logger.log("Phone not reachable", tvName);
156 | logger.log("TCP polling thread - Unable to reach phone on " + addr, "log");
157 | stopSelf();
158 | }
159 |
160 | Log.d(TAG, "tcp - connecting to phone" );
161 | logger.log("TCP polling thread - Opening connection to phone", "log");
162 | phoneTcpSocket = new Socket();
163 | phoneTcpSocket.setSoTimeout(5000);
164 | phoneTcpSocket.connect(new InetSocketAddress(gatewayIP, 5277), 500);
165 | Log.d(TAG, "tcp - connected");
166 | logger.log("TCP polling thread - Opening Socket to phone", "log");
167 | socketoutput = phoneTcpSocket.getOutputStream();
168 | socketinput = new DataInputStream(phoneTcpSocket.getInputStream());
169 | socketoutput.write(new byte[]{0, 3, 0, 6, 0, 1, 0, 1, 0, 2});
170 | socketoutput.flush();
171 |
172 | byte[] recv = new byte[12];
173 | socketinput.read(recv);
174 | Log.d(TAG, "tcp - recv from phone " + bytesToHex(recv));
175 | localCompleted = true;
176 | logger.log("TCP Polling thread recv from phone " + bytesToHex(recv), "log");
177 |
178 | } catch (Exception e) {
179 | Log.e(TAG, "tcp - error opening phone " + e.getMessage());
180 | logger.log("TCP polling thread - error opening phone " + e.getMessage(), "log");
181 | stopSelf();
182 | }
183 |
184 | //wait for usb initialization
185 | if (!usbCompleted && running)
186 | Log.d(TAG, "tcp - waiting for usb");
187 | while (!usbCompleted && running) {
188 | try {
189 | sleep(10);
190 | } catch (InterruptedException e) {
191 | Log.e(TAG, "tcp - error sleeping "+e.getMessage());
192 | logger.log("TCP error sleeping = " + e.getMessage(), "log");
193 | }
194 | }
195 |
196 | while (running)
197 | {
198 | try {
199 | getLocalmessage();
200 |
201 | } catch (Exception e) {
202 | Log.e(TAG,"tcp - in main loop "+e.getMessage());
203 | logger.log("TCP error in main loop = " + e.getMessage(), "log");
204 | stopSelf();
205 | break;
206 | }
207 | }
208 | Log.d(TAG,"tcp - end");
209 | logger.log("tcp end",tvName);
210 | stopSelf();
211 | }
212 |
213 | }
214 |
215 | class usbpollthread implements Runnable {
216 |
217 | public void run() {
218 | Looper.prepare();
219 | Log.d(TAG,"usb - run");
220 |
221 | byte[] buf = new byte[16384];
222 | int x;
223 |
224 | try {
225 | x=phoneInputStream.read(buf);
226 | Log.d(TAG, "usb -received from usb "+bytesToHex((Arrays.copyOf(buf, x))));
227 | logger.log("received from usb",tvName);
228 | phoneOutputStream.write(new byte[]{0, 3, 0, 8, 0, 2, 0, 1, 0, 4, 0, 0});
229 | usbCompleted = true;
230 | } catch (Exception e) {
231 | Log.e(TAG, "usb - error init "+e.getMessage());
232 | stopSelf();
233 | }
234 |
235 | if (!localCompleted && running) {
236 | Log.d(TAG, "usb - waiting for local");
237 | logger.log("usb waiting for local",tvName);
238 | }
239 | int i = 0;
240 | while (!localCompleted && running) {
241 | i++;
242 | try {
243 | sleep(100);
244 | if ((i % 10) == 0) {
245 | logger.log("usb waiting for local count " + i,tvName);
246 | }
247 | } catch (InterruptedException e) {
248 | Log.e(TAG, "usb - error sleeping "+e.getMessage());
249 | }
250 | }
251 |
252 | while (running)
253 | {
254 | try {
255 | x = phoneInputStream.read(buf);
256 | processCarMessage(Arrays.copyOf(buf, x));
257 | }
258 | catch (Exception e)
259 | {
260 | Log.e(TAG,"usb - in main loop " + e.getMessage());
261 | stopSelf();
262 | }
263 |
264 | }
265 | Log.d(TAG,"usb - end");
266 | stopSelf();
267 | }
268 | }
269 |
270 | private void getLocalmessage() throws IOException {
271 | int enc_len;
272 | socketinput.readFully(readbuffer,0,4);
273 | int pos=4;
274 | enc_len = (readbuffer[2] & 0xFF) << 8 | (readbuffer[3] & 0xFF);
275 | if ((int) readbuffer[1] == 9) //Flag 9 means the header is 8 bytes long (read it in a separate byte array)
276 | {
277 | pos+=4;
278 | socketinput.readFully(readbuffer,4,4);
279 | }
280 | socketinput.readFully(readbuffer,pos,enc_len);
281 | phoneOutputStream.write(Arrays.copyOf(readbuffer,enc_len+pos));
282 |
283 | }
284 |
285 | private void processCarMessage(final byte[] buf) throws IOException {
286 | socketoutput.write(buf);
287 | }
288 |
289 | @Override
290 | public void onDestroy() {
291 | // Attempt to close phone connection gracefully
292 | if (phoneTcpSocket != null) {
293 | try {
294 | socketoutput.close();
295 | socketinput.close();
296 | phoneTcpSocket.close();
297 | } catch (IOException e) {
298 | Log.d(TAG, "error closing phone tcp socket " + e.getMessage());
299 | logger.log("error closing phone tcp socket",tvName);
300 | }
301 | } else {
302 | // If phone socket not open, going to try connect and close it to make it graceful
303 | try {
304 | phoneTcpSocket = new Socket();
305 | phoneTcpSocket.setSoTimeout(5000);
306 | phoneTcpSocket.connect(new InetSocketAddress(gatewayIP, 5277), 500);
307 | socketoutput = phoneTcpSocket.getOutputStream();
308 | socketinput = new DataInputStream(phoneTcpSocket.getInputStream());
309 | socketoutput.write(new byte[]{0, 3, 0, 6, 0, 1, 0, 1, 0, 2});
310 | socketoutput.flush();
311 | socketoutput.close();
312 | socketinput.close();
313 | phoneTcpSocket.close();
314 | } catch (Exception e) {
315 | e.printStackTrace();
316 | Log.d(TAG, "error trying to clean up tcp socket " + e.getMessage());
317 | logger.log("error trying to clean up tcp socket",tvName);
318 | }
319 | }
320 | // Attempt to close usb connection gracefully
321 | if (mFileDescriptor != null) {
322 | try {
323 | phoneInputStream.close();
324 | phoneOutputStream.close();
325 | mFileDescriptor.close();
326 | } catch (IOException e) {
327 | Log.d(TAG, "error closing usb " + e.getMessage());
328 | logger.log("error closing usb",tvName);
329 | }
330 | }
331 | Log.d(TAG,"service destroyed");
332 | logger.log("Service Destroyed", "log");
333 | resetService();
334 | mNotificationManager.cancelAll();
335 | running=false;
336 | }
337 |
338 | private void resetService() {
339 | Intent intent = new Intent();
340 | intent.setAction(ACTION_RESET_AASERVICE);
341 | sendBroadcast(intent);
342 | }
343 |
344 | private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
345 | public static String bytesToHex(byte[] bytes) {
346 | char[] hexChars = new char[bytes.length * 2];
347 | for ( int j = 0; j < bytes.length; j++ ) {
348 | int v = bytes[j] & 0xFF;
349 | hexChars[j * 2] = hexArray[v >>> 4];
350 | hexChars[j * 2 + 1] = hexArray[v & 0x0F];
351 | }
352 | return new String(hexChars);
353 | }
354 |
355 | }
356 |
--------------------------------------------------------------------------------
/app/src/main/java/com/north3221/aagateway/ConnectionStateReceiver.java:
--------------------------------------------------------------------------------
1 | package com.north3221.aagateway;
2 |
3 | import static com.north3221.aagateway.MainActivity.SHARED_PREF_NAME;
4 | import static com.north3221.aagateway.MainActivity.TAG;
5 |
6 | import android.annotation.SuppressLint;
7 | import android.app.AlarmManager;
8 | import android.app.PendingIntent;
9 | import android.content.BroadcastReceiver;
10 | import android.content.Context;
11 | import android.content.Intent;
12 | import android.content.IntentFilter;
13 | import android.content.SharedPreferences;
14 | import android.hardware.usb.UsbAccessory;
15 | import android.hardware.usb.UsbManager;
16 | import android.net.ConnectivityManager;
17 | import android.net.DhcpInfo;
18 | import android.net.NetworkInfo;
19 | import android.net.wifi.WifiManager;
20 | import android.os.BatteryManager;
21 | import android.os.Build;
22 | import android.os.CountDownTimer;
23 | import android.os.PowerManager;
24 | import android.text.format.Formatter;
25 | import android.util.Log;
26 | import android.widget.Toast;
27 | import java.io.IOException;
28 |
29 | public class ConnectionStateReceiver extends BroadcastReceiver {
30 | private AAlogger logger;
31 | private static CountDownTimer powerCountDown;
32 | private static PowerManager.WakeLock wakeLock;
33 | private static Boolean wifiConnected;
34 | private static UsbAccessory usbAccessory;
35 | private static final int intAlarmCode = 23965;
36 |
37 | public static final String
38 | ACTION_USB_ACCESSORY_ATTACHED = "com.north3221.aagateway.ACTION_USB_ACCESSORY_ATTACHED",
39 | ACTION_USB_ACCESSORY_DETACHED = "com.north3221.aagateway.ACTION_USB_ACCESSORY_DETACHED",
40 | ACTION_RESET_AASERVICE = "com.north3221.aagateway.ACTION_RESET_AA_SERVICE",
41 | ACTION_CHECK_SERVICE_REMINDER = "com.north3221.aagateway.ACTION_RESET_AA_SERVICE_REMINDER",
42 | SHARED_PREF_KEY_WIFI_CONTROL = "WIFI_CONTROL",
43 | SHARED_PREF_KEY_USB_CONTROL_TYPE = "USB_CONTROL";
44 | private static final String
45 | SERVICE_REMINDER_EXTRA = "CALL_COUNT";
46 | @Override
47 | public void onReceive(Context context, Intent intent) {
48 |
49 | String action = intent.getAction();
50 | if (action == null){
51 | return;
52 | }
53 | logger = new AAlogger(context);
54 | String device = "Power";
55 |
56 | switch (action){
57 | case ConnectivityManager.CONNECTIVITY_ACTION:
58 | wifiConnectivityAction(context, intent);
59 | break;
60 | case ACTION_USB_ACCESSORY_ATTACHED:
61 | usbDeviceAttachedAction(context, intent);
62 | break;
63 | case ACTION_USB_ACCESSORY_DETACHED:
64 | device = "Android Auto Device";
65 | case Intent.ACTION_POWER_DISCONNECTED:
66 | usbDeviceDetachedAction(context, device);
67 | break;
68 | case Intent.ACTION_POWER_CONNECTED:
69 | logger.log("USB Power Connected", "usbconnection");
70 | if (powerCountDown != null){
71 | powerCountDown.cancel();
72 | }
73 | setWakeLock(context,true);
74 | setWifi(context, true);
75 | break;
76 | case ACTION_RESET_AASERVICE:
77 | resetAAService(context);
78 | break;
79 | case ACTION_CHECK_SERVICE_REMINDER:
80 | checkServiceReminderAction(context,intent);
81 | break;
82 | default:
83 | Toast.makeText(context,"Received unknown action: " + action,Toast.LENGTH_SHORT).show();
84 | }
85 |
86 | }
87 |
88 | private void wifiConnectivityAction(Context context, Intent intent){
89 | NetworkInfo ni = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
90 | if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {
91 | wifiConnected = ni.isConnected();
92 | logger.log("Wifi Connected:= " + wifiConnected.toString(), "wificonnection");
93 | requestServiceState(context, wifiConnected, "wifi");
94 | }
95 |
96 | }
97 |
98 | private String getGatewayIP (Context context) {
99 | try {
100 | WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
101 | DhcpInfo dhcp;
102 | if (wm != null) {
103 | dhcp = wm.getDhcpInfo();
104 | if (dhcp.gateway != 0) {
105 | return Formatter.formatIpAddress(dhcp.gateway);
106 | }
107 | }
108 | } catch (Exception ignored) {
109 | return "ERROR";
110 | }
111 | return "NO IP";
112 | }
113 |
114 | public void usbDeviceAttachedAction(Context context, Intent usbIntent){
115 | logger.log("USB Android Auto Device connected","usbconnection");
116 | if (usbIntent.hasExtra(UsbManager.EXTRA_ACCESSORY)) {
117 | usbAccessory = usbIntent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
118 | requestServiceState(context, true, "usb");
119 | }
120 | }
121 |
122 | private boolean isUsbAttached(Context context){
123 | return getUsbAccessory(context) != null;
124 | }
125 |
126 | private UsbAccessory getUsbAccessory (Context context){
127 | if (usbAccessory != null)
128 | return usbAccessory;
129 |
130 | UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
131 | if (manager != null) {
132 | UsbAccessory[] accessoryList = manager.getAccessoryList();
133 | if (accessoryList != null && accessoryList.length > 0 ) {
134 | for (UsbAccessory usbAccessory : accessoryList) {
135 | if (usbAccessory.getManufacturer().equalsIgnoreCase("Android")) {
136 | return usbAccessory;
137 | }
138 | }
139 | }
140 | }
141 | return null;
142 | }
143 |
144 | private void usbDeviceDetachedAction(final Context context, final String device) {
145 | logger.log("USB " + device + " Disconnected timer started", "usbconnection");
146 | usbAccessory = null;
147 |
148 | if (powerCountDown != null){
149 | powerCountDown.cancel();
150 | }
151 | powerCountDown = new CountDownTimer(3000, 500) {
152 | public void onTick(long millisUntilFinished) {
153 | if (isPowerConnected(context)) {
154 | logger.log("USB Power connected during power off timer", "log");
155 | logger.log("USB " + device + " Connected", "usbconnection");
156 | cancel();
157 | }
158 | }
159 | public void onFinish() {
160 | if (!isPowerConnected(context)) {
161 | requestServiceState(context, false, "usb");
162 | setWifi(context, false);
163 | setWakeLock(context, false);
164 | logger.log("USB Power disconnected", "usbconnection");
165 | } else {
166 | logger.log("USB Power connected during power off timer", "log");
167 | logger.log("USB " + device + " Connected", "usbconnection");
168 | }
169 | }
170 |
171 | }.start();
172 |
173 | }
174 |
175 | private void setWifi(final Context context, boolean tostate){
176 | SharedPreferences sp = context.getApplicationContext().getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
177 | if (!sp.getBoolean(SHARED_PREF_KEY_WIFI_CONTROL,true)){
178 | return;
179 | }
180 | WifiManager wifi = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
181 | if (wifi != null) {
182 | if (tostate != wifi.isWifiEnabled()){
183 | wifi.setWifiEnabled(tostate);
184 | logger.log("WiFi enabled set to " + tostate, "wificonnection");
185 | }
186 | }
187 |
188 | }
189 |
190 | private void setWakeLock (Context context,boolean wake){
191 | String WLTAG = TAG + ":WakeLock";
192 |
193 | if (wake) {
194 | //private static CountDownTimer wakeCountDown;
195 | PowerManager powerManager = (PowerManager) context.getApplicationContext().getSystemService(Context.POWER_SERVICE);
196 | if (powerManager != null) {
197 | wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, WLTAG);
198 | // 5 mins timeout
199 | wakeLock.acquire(5*60*1000L);
200 | }
201 |
202 | } else{
203 | if (wakeLock != null) {
204 | wakeLock.release();
205 | logger.log("Released wakelock", "");
206 | Log.d(WLTAG,"Released Wakelock");
207 | }
208 | }
209 |
210 | }
211 |
212 | private void requestServiceState(Context context,boolean reqState, String type){
213 | UsbAccessory usb = getUsbAccessory(context);
214 | String gatewayIP = getGatewayIP(context);
215 | logger.log("Requested service: " + reqState + " - Current state: " + HackerService.running, "log");
216 | logger.log("Gateway IP: " + gatewayIP + " - USB attached : " + isUsbAttached(context),"log");
217 | // If requested running and its not, perform checks see if we can
218 | if (reqState && !HackerService.running) {
219 | if (type.equals("wifi") && !isUsbAttached(context)) {
220 | logger.log("Waiting on USB", "aaservice");
221 | return;
222 | }
223 | if (!(gatewayIP.length() > 5)) {
224 | logger.log("Cant start Service (no gw ip)", "aaservice");
225 | }
226 | if (usb == null){
227 | logger.log("Cant start Service (no usb)", "aaservice");
228 | return;
229 | }
230 | if (type.equals("usb") && !isWifiConnected(context)) {
231 | logger.log("Waiting on WiFi", "aaservice");
232 | return;
233 | }
234 | }
235 |
236 | if (reqState != HackerService.running){
237 | if (type.equals("wifi")) {
238 | toggleUSB(context);
239 | } else {
240 | updateServiceState(context, reqState, gatewayIP, usb);
241 | }
242 | }
243 | }
244 |
245 | private void updateServiceState(Context context, boolean reqState, String gatewayIP, UsbAccessory usbAccessory){
246 | Intent hsIntent = new Intent(context, HackerService.class);
247 | if (reqState) {
248 | logger.log("Starting Service", "log");
249 | hsIntent.putExtra("gwip", gatewayIP);
250 | hsIntent.putExtra("accessory", usbAccessory);
251 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
252 | context.startForegroundService(hsIntent);
253 | } else {
254 | context.startService(hsIntent);
255 | }
256 | checkServiceReminder(context,0);
257 | } else {
258 | logger.log("Stopping Service", "log");
259 | context.stopService(hsIntent);
260 | cancelServiceReminder(context);
261 | }
262 |
263 | }
264 |
265 | private boolean isWifiConnected(Context context) {
266 | if (wifiConnected != null)
267 | return wifiConnected;
268 | try {
269 | ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
270 | if (manager != null) {
271 | NetworkInfo networkInfo = manager.getActiveNetworkInfo();
272 | logger.log("isWiFiConnected got Connectivity Manager");
273 | wifiConnected = (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) && networkInfo.isConnected();
274 | } else {
275 | logger.log("isWiFiConnected failed to get Connectivity Manager");
276 | }
277 | } catch (Exception e) {
278 | Log.e("WIFI CONNECTION", "Error checking WiFi := " + e);
279 | }
280 | return wifiConnected != null && wifiConnected;
281 | }
282 |
283 | private void toggleUSB(Context context){
284 | logger.log("Toggling USB","log");
285 | // NB Root is required!
286 | // NBB Doesnt work on all devices....
287 | String[] cmdOne = {"su", "-c", "svc", "usb", "setFunctions"};
288 | String[] cmdTwo = {"su", "-c", "svc", "usb", "setFunctions", "mtp", "true"};
289 |
290 | // Alternate method
291 | SharedPreferences sp = context.getApplicationContext().getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
292 | if (sp.getBoolean(SHARED_PREF_KEY_USB_CONTROL_TYPE,false)){
293 | logger.log("Toggling USB - Alternative","log");
294 | cmdOne = new String[]{"su", "-c", "settings", "put", "global", "adb_enabled", "0"};
295 | cmdTwo = new String[]{"su", "-c", "settings", "put", "global", "adb_enabled", "1"};
296 | }
297 |
298 | try {
299 | Process p = Runtime.getRuntime().exec(cmdOne);
300 | p.waitFor();
301 | p = Runtime.getRuntime().exec(cmdTwo);
302 | p.waitFor();
303 |
304 | } catch (IOException | InterruptedException e) {
305 | e.printStackTrace();
306 | Log.e("USB CONN","ERROR", e);
307 | }
308 | }
309 |
310 | /*
311 | // Keep this here in case anyone has issues waking device on power
312 | private void wakeDevice(final Context context){
313 | logger.log("Waking Device","log");
314 |
315 | wakeCountDown = new CountDownTimer(30000, 5000) {
316 | public void onTick(long millisUntilFinished) {
317 | // NB Root is required!
318 | if (isWifiConnected(context) || HackerService.running)
319 | cancel();
320 | String[] cmdWake = {"su", "-c", "input", "keyevent", "KEYCODE_WAKEUP"};
321 | try {
322 | Process p = Runtime.getRuntime().exec(cmdWake);
323 | p.waitFor();
324 | } catch (IOException | InterruptedException e) {
325 | e.printStackTrace();
326 | Log.e("WAKE DEVICE","ERROR", e);
327 | }
328 | }
329 | public void onFinish() {
330 | checkServiceReminder(context,0);
331 | }
332 |
333 | }.start();
334 |
335 | }
336 |
337 | */
338 |
339 | private void resetAAService(Context context){
340 | logger.log("Reset Service Requested","aaservice");
341 | if (HackerService.running)
342 | logger.log("Reset Service Stopping Service","aaservice");
343 | updateServiceState(context,false, "", null);
344 | if ((isUsbAttached(context) || isPowerConnected(context)) && isWifiConnected(context))
345 | toggleUSB(context);
346 | }
347 |
348 | private boolean isPowerConnected(Context context) {
349 | Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
350 | int plugged = 0;
351 | if (intent != null) plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
352 | return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
353 | }
354 |
355 | private void checkServiceReminderAction(Context context, Intent intent){
356 | int count = intent.getIntExtra(SERVICE_REMINDER_EXTRA,0);
357 | if (isWifiConnected(context) && isUsbAttached(context) && !HackerService.running){
358 | cancelServiceReminder(context);
359 | toggleUSB(context);
360 | } else {
361 | if (count < 3) checkServiceReminder(context, count);
362 | }
363 |
364 | }
365 | private void checkServiceReminder(Context context, int count) {
366 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
367 | AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
368 | Intent ri = createReminderIntent();
369 | ri.putExtra(SERVICE_REMINDER_EXTRA, count + 1);
370 | PendingIntent piServiceReminder;
371 | piServiceReminder = createServiceReminderPendingIntent(context, ri);
372 |
373 | if (alarmManager != null) {
374 | piServiceReminder.cancel();
375 | alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 30000, piServiceReminder);
376 | alarmManager.cancel(piServiceReminder);
377 | }
378 | }
379 | }
380 |
381 | private void cancelServiceReminder(Context context){
382 | AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
383 | PendingIntent pi = createServiceReminderPendingIntent(context);
384 | pi.cancel();
385 | if (alarmManager != null) {
386 | alarmManager.cancel(pi);
387 | }
388 | }
389 |
390 | private Intent createReminderIntent(){
391 | Intent intent = new Intent();
392 | intent.setAction(ACTION_CHECK_SERVICE_REMINDER);
393 | return intent;
394 | }
395 |
396 | private PendingIntent createServiceReminderPendingIntent(Context context){
397 | return createServiceReminderPendingIntent(context,createReminderIntent());
398 | }
399 |
400 | @SuppressLint("UnspecifiedImmutableFlag")
401 | private PendingIntent createServiceReminderPendingIntent(Context context, Intent reminderIntent){
402 | PendingIntent pi;
403 | pi = PendingIntent.getBroadcast(context,intAlarmCode,reminderIntent,PendingIntent.FLAG_UPDATE_CURRENT);
404 | return pi;
405 | }
406 |
407 |
408 |
409 |
410 | }
411 |
--------------------------------------------------------------------------------