Massive rewrite

This commit is contained in:
Electric1447
2021-08-25 00:54:29 +03:00
parent 3b497cc526
commit 33eb36eb6a
24 changed files with 1075 additions and 690 deletions
+10 -9
View File
@@ -3,6 +3,7 @@
package="com.dosse.airpods">
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
@@ -25,7 +26,7 @@
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:name=".ui.MainActivity"
android:exported="true"
android:launchMode="singleTop">
<intent-filter>
@@ -35,28 +36,28 @@
</activity>
<activity
android:name=".AboutActivity"
android:name=".ui.AboutActivity"
android:label="@string/about"
android:launchMode="singleTop"
android:parentActivityName=".SettingsActivity" />
android:parentActivityName=".ui.SettingsActivity" />
<activity
android:name=".SettingsActivity"
android:name=".ui.SettingsActivity"
android:label="@string/settings"
android:launchMode="singleTop"
android:parentActivityName=".MainActivity" />
android:parentActivityName=".ui.MainActivity" />
<activity
android:name=".NoBTActivity"
android:name=".ui.NoBTActivity"
android:label="@string/app_name" />
<activity
android:name=".IntroActivity"
android:name=".ui.IntroActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar" />
<receiver
android:name=".Starter"
android:name=".receivers.Starter"
android:enabled="true"
android:exported="true"
android:label="@string/app_name">
@@ -67,7 +68,7 @@
</receiver>
<service
android:name=".PodsService"
android:name=".pods.PodsService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="location" />
@@ -1,614 +0,0 @@
package com.dosse.airpods;
import static com.dosse.airpods.utils.ScannerUtils.isMax;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanFilter.Builder;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.preference.PreferenceManager;
import com.dosse.airpods.utils.NotificationUtils;
import com.dosse.airpods.utils.PermissionUtils;
import com.dosse.airpods.utils.ScannerUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
/**
* This is the class that does most of the work. It has 3 functions:
* - Detect when AirPods are detected
* - Receive beacons from AirPods and decode them (easier said than done thanks to google's autism)
* - Display the notification with the status
*/
public class PodsService extends Service {
private static void OpenPodsDebugLog (String msg) {
if (BuildConfig.DEBUG) Log.d(TAG, msg); // Log is only displayed if this is a debug build, not release
}
private static BluetoothLeScanner btScanner;
private static int leftStatus = 15, rightStatus = 15, caseStatus = 15, maxStatus = 15;
private static boolean chargeL = false, chargeR = false, chargeCase = false;
private static boolean inEarL = false, inEarR = false;
public static final String MODEL_AIRPODS_NORMAL = "airpods12", MODEL_AIRPODS_PRO = "airpodspro", MODEL_AIRPODS_MAX = "airpodsmax";
public static String model = MODEL_AIRPODS_NORMAL;
/**
* The following method (startAirPodsScanner) creates a bluetooth LE scanner.
* This scanner receives all beacons from nearby BLE devices (not just your devices!) so we need to do 3 things:
* - Check that the beacon comes from something that looks like a pair of AirPods
* - Make sure that it is YOUR pair of AirPods
* - Decode the beacon to get the status
* <p>
* On a normal OS, we would use the bluetooth address of the device to filter out beacons from other devices.
* UNFORTUNATELY, someone at google was so concerned about privacy (yea, as if they give a shit) that he decided it was a good idea to not allow access to the bluetooth address of incoming BLE beacons.
* As a result, we have no reliable way to make sure that the beacon comes from YOUR airpods and not the guy sitting next to you on the bus.
* What we did to workaround this issue is this:
* - When a beacon arrives that looks like a pair of AirPods, look at the other beacons received in the last 10 seconds and get the strongest one
* - If the strongest beacon's fake address is the same as this, use this beacon; otherwise use the strongest beacon
* - Filter for signals stronger than -60db
* - Decode...
* <p>
* Decoding the beacon:
* This was done through reverse engineering. Hopefully it's correct.
* - The beacon coming from a pair of AirPods contains a manufacturer specific data field n°76 of 27 bytes
* - We convert this data to a hexadecimal string
* - The 12th and 13th characters in the string represent the charge of the left and right pods. Under unknown circumstances[1], they are right and left instead (see isFlipped). Values between 0 and 10 are battery 0-100%; Value 15 means it's disconnected
* - The 15th character in the string represents the charge of the case. Values between 0 and 10 are battery 0-100%; Value 15 means it's disconnected
* - The 14th character in the string represents the "in charge" status. Bit 0 (LSB) is the left pod; Bit 1 is the right pod; Bit 2 is the case. Bit 3 might be case open/closed but I'm not sure and it's not used
* - The 11th character in the string represents the in-ear detection status. Bit 1 is the left pod; Bit 3 is the right pod.
* - The 7th character in the string represents the AirPods model (E=AirPods pro)
* <p>
* After decoding a beacon, the status is written to leftStatus, rightStatus, caseStatus, maxStatus, chargeL, chargeR, chargeCase, inEarL, inEarR so that the NotificationThread can use the information
* <p>
* Notes:
* 1) - isFlipped set by bit 1 of 10th character in the string; seems to be related to in-ear detection;
*/
private static final ArrayList<ScanResult> recentBeacons = new ArrayList<>();
private static final long RECENT_BEACONS_MAX_T_NS = 10000000000L; //10s
private void startAirPodsScanner () {
try {
OpenPodsDebugLog("START SCANNER");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
BluetoothManager btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
assert btManager != null;
BluetoothAdapter btAdapter = btManager.getAdapter();
if (prefs.getBoolean("batterySaver", false)) {
if (btScanner != null) {
btScanner.stopScan(new ScanCallback() {
@Override
public void onScanResult (int callbackType, ScanResult result) {
}
});
}
}
btScanner = btAdapter.getBluetoothLeScanner();
if (!btAdapter.isEnabled())
throw new Exception("BT Off");
List<ScanFilter> filters = getScanFilters();
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(prefs.getBoolean("batterySaver", false) ? ScanSettings.SCAN_MODE_LOW_POWER : ScanSettings.SCAN_MODE_LOW_LATENCY)
.setReportDelay(1)
.build();
btScanner.startScan(filters, settings, new ScanCallback() {
@Override
public void onBatchScanResults (List<ScanResult> scanResults) {
for (ScanResult result : scanResults)
onScanResult(-1, result);
super.onBatchScanResults(scanResults);
}
@Override
public void onScanResult (int callbackType, ScanResult result) {
try {
byte[] data = Objects.requireNonNull(result.getScanRecord()).getManufacturerSpecificData(76);
if (data == null || data.length != 27)
return;
recentBeacons.add(result);
OpenPodsDebugLog(String.format(Locale.getDefault(), "%ddb", result.getRssi()));
OpenPodsDebugLog(ScannerUtils.decodeHex(data));
ScanResult strongestBeacon = null;
for (int i = 0; i < recentBeacons.size(); i++) {
if (SystemClock.elapsedRealtimeNanos() - recentBeacons.get(i).getTimestampNanos() > RECENT_BEACONS_MAX_T_NS) {
recentBeacons.remove(i--);
continue;
}
if (strongestBeacon == null || strongestBeacon.getRssi() < recentBeacons.get(i).getRssi())
strongestBeacon = recentBeacons.get(i);
}
if (strongestBeacon != null && strongestBeacon.getDevice().getAddress().equals(result.getDevice().getAddress()))
strongestBeacon = result;
result = strongestBeacon;
assert result != null;
if (result.getRssi() < -60)
return;
String a = ScannerUtils.decodeHex(Objects.requireNonNull(Objects.requireNonNull(result.getScanRecord()).getManufacturerSpecificData(76)));
boolean flip = ScannerUtils.isFlipped(a);
leftStatus = Integer.parseInt("" + a.charAt(flip ? 12 : 13), 16); // Left airpod (0-10 batt; 15=disconnected)
rightStatus = Integer.parseInt("" + a.charAt(flip ? 13 : 12), 16); // Right airpod (0-10 batt; 15=disconnected)
caseStatus = Integer.parseInt("" + a.charAt(15), 16); // Case (0-10 batt; 15=disconnected)
maxStatus = Integer.parseInt("" + a.charAt(13), 16); // Airpods max (0-10 batt; 15=disconnected)
int chargeStatus = Integer.parseInt("" + a.charAt(14), 16); // Charge status (bit 0=left; bit 1=right; bit 2=case)
chargeL = (chargeStatus & (flip ? 0b00000010 : 0b00000001)) != 0;
chargeR = (chargeStatus & (flip ? 0b00000001 : 0b00000010)) != 0;
chargeCase = (chargeStatus & 0b00000100) != 0;
int inEarStatus = Integer.parseInt("" + a.charAt(11), 16); // InEar status (bit 1=left; bit 3=right)
inEarL = (inEarStatus & (flip ? 0b00001000 : 0b00000010)) != 0;
inEarR = (inEarStatus & (flip ? 0b00000010 : 0b00001000)) != 0;
switch (a.charAt(7)) { // Detect if these are AirPods Pro/Max or regular ones
case 'E': model = MODEL_AIRPODS_PRO; break;
case 'A': model = MODEL_AIRPODS_MAX; break;
default: model = MODEL_AIRPODS_NORMAL;
}
lastSeenConnected = System.currentTimeMillis();
} catch (Throwable t) {
OpenPodsDebugLog("" + t);
}
}
});
} catch (Throwable t) {
OpenPodsDebugLog("" + t);
}
}
private List<ScanFilter> getScanFilters () {
byte[] manufacturerData = new byte[27];
byte[] manufacturerDataMask = new byte[27];
manufacturerData[0] = 7;
manufacturerData[1] = 25;
manufacturerDataMask[0] = -1;
manufacturerDataMask[1] = -1;
Builder builder = new Builder();
builder.setManufacturerData(76, manufacturerData, manufacturerDataMask);
return Collections.singletonList(builder.build());
}
private void stopAirPodsScanner () {
try {
if (btScanner != null) {
OpenPodsDebugLog("STOP SCANNER");
btScanner.stopScan(new ScanCallback() {
@Override
public void onScanResult (int callbackType, ScanResult result) {
}
});
}
leftStatus = 15;
rightStatus = 15;
caseStatus = 15;
maxStatus = 15;
} catch (Throwable ignored) {
}
}
/**
* The following class is a thread that manages the notification while your AirPods are connected.
* <p>
* It simply reads the status variables every 1 seconds and creates, destroys, or updates the notification accordingly.
* The notification is shown when BT is on and AirPods are connected. The status is updated every 1 second. Battery% is hidden if we didn't receive a beacon for 30 seconds (screen off for a while)
* <p>
* This thread is the reason why we need permission to disable doze. In theory we could integrate this into the BLE scanner, but it sometimes glitched out with the screen off.
*/
private static NotificationThread n = null;
private static final String TAG = "AirPods";
private static long lastSeenConnected = 0;
private static final long TIMEOUT_CONNECTED = 30000;
private static boolean maybeConnected = false;
private class NotificationThread extends Thread {
private final NotificationManager mNotifyManager;
@SuppressWarnings("WeakerAccess")
public NotificationThread () {
mNotifyManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// On Oreo (API27) and newer, create a notification channel.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(TAG, TAG, NotificationManager.IMPORTANCE_LOW);
channel.setSound(null, null);
channel.enableVibration(false);
channel.enableLights(false);
channel.setShowBadge(false);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mNotifyManager.createNotificationChannel(channel);
}
}
public void run () {
boolean notificationShowing = false;
String compat = getPackageManager().getInstallerPackageName(getPackageName());
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(PodsService.this, TAG);
mBuilder.setShowWhen(false);
mBuilder.setOngoing(true);
mBuilder.setSmallIcon(R.mipmap.notification_icon);
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
for (; ; ) {
RemoteViews[] notificationArr = new RemoteViews[] {new RemoteViews(getPackageName(), R.layout.status_big), new RemoteViews(getPackageName(), R.layout.status_small)};
RemoteViews[] notificationLocation = new RemoteViews[] {new RemoteViews(getPackageName(), R.layout.location_disabled_big), new RemoteViews(getPackageName(), R.layout.location_disabled_small)};
if (maybeConnected && !(leftStatus == 15 && rightStatus == 15 && caseStatus == 15 && maxStatus == 15)) {
if (!notificationShowing) {
OpenPodsDebugLog("Creating notification");
notificationShowing = true;
mNotifyManager.notify(1, mBuilder.build());
}
} else {
if (notificationShowing) {
OpenPodsDebugLog("Removing notification");
notificationShowing = false;
continue;
}
mNotifyManager.cancel(1);
}
// Apparently this restriction was removed ONLY in android Q
if (PermissionUtils.getLocationPermissions(getApplicationContext()) || Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
mBuilder.setCustomContentView(notificationArr[1]);
mBuilder.setCustomBigContentView(notificationArr[0]);
} else {
mBuilder.setCustomContentView(notificationLocation[1]);
mBuilder.setCustomBigContentView(notificationLocation[0]);
}
if (notificationShowing) {
OpenPodsDebugLog(isMax() ? String.format(Locale.getDefault(), "Battery: %d Model: %s", maxStatus, model) :
String.format(Locale.getDefault(), "Left: %d%s%s Right: %d%s%s Case: %d%s Model: %s",
leftStatus, chargeL ? "+" : "", inEarL ? "$" : "",
rightStatus, chargeR ? "+" : "", inEarR ? "$" : "",
caseStatus, chargeCase ? "+" : "", model)
);
switch (model) {
case MODEL_AIRPODS_NORMAL:
for (RemoteViews notification : notificationArr) {
notification.setImageViewResource(R.id.leftPodImg, leftStatus <= 10 ? R.drawable.pod : R.drawable.pod_disconnected);
notification.setImageViewResource(R.id.rightPodImg, rightStatus <= 10 ? R.drawable.pod : R.drawable.pod_disconnected);
notification.setImageViewResource(R.id.podCaseImg, caseStatus <= 10 ? R.drawable.pod_case : R.drawable.pod_case_disconnected);
}
break;
case MODEL_AIRPODS_PRO:
for (RemoteViews notification : notificationArr) {
notification.setImageViewResource(R.id.leftPodImg, leftStatus <= 10 ? R.drawable.podpro : R.drawable.podpro_disconnected);
notification.setImageViewResource(R.id.rightPodImg, rightStatus <= 10 ? R.drawable.podpro : R.drawable.podpro_disconnected);
notification.setImageViewResource(R.id.podCaseImg, caseStatus <= 10 ? R.drawable.podpro_case : R.drawable.podpro_case_disconnected);
}
break;
case MODEL_AIRPODS_MAX:
for (RemoteViews notification : notificationArr)
notification.setImageViewResource(R.id.leftPodImg, maxStatus <= 10 ? R.drawable.podmax : R.drawable.podmax_disconnected);
}
for (RemoteViews notification : notificationArr) {
notification.setViewVisibility(R.id.rightPod, isMax() ? View.GONE : View.VISIBLE);
notification.setViewVisibility(R.id.podCase, isMax() ? View.GONE : View.VISIBLE);
}
if (System.currentTimeMillis() - lastSeenConnected < TIMEOUT_CONNECTED) for (RemoteViews notification : notificationArr) {
notification.setViewVisibility(R.id.leftPodText, View.VISIBLE);
notification.setViewVisibility(R.id.rightPodText, View.VISIBLE);
notification.setViewVisibility(R.id.podCaseText, View.VISIBLE);
notification.setViewVisibility(R.id.leftPodUpdating, View.INVISIBLE);
notification.setViewVisibility(R.id.rightPodUpdating, View.INVISIBLE);
notification.setViewVisibility(R.id.podCaseUpdating, View.INVISIBLE);
notification.setTextViewText(R.id.leftPodText, NotificationUtils.statusToString(isMax() ? maxStatus : leftStatus));
notification.setTextViewText(R.id.rightPodText, NotificationUtils.statusToString(rightStatus));
notification.setTextViewText(R.id.podCaseText, NotificationUtils.statusToString(caseStatus));
notification.setImageViewResource(R.id.leftBatImg, NotificationUtils.batImgSrcId(chargeL));
notification.setImageViewResource(R.id.rightBatImg, NotificationUtils.batImgSrcId(chargeR));
notification.setImageViewResource(R.id.caseBatImg, NotificationUtils.batImgSrcId(chargeCase));
notification.setViewVisibility(R.id.leftBatImg, NotificationUtils.batImgVisibility(chargeL, leftStatus));
notification.setViewVisibility(R.id.rightBatImg, NotificationUtils.batImgVisibility(chargeR, rightStatus));
notification.setViewVisibility(R.id.caseBatImg, NotificationUtils.batImgVisibility(chargeCase, caseStatus));
notification.setViewVisibility(R.id.leftInEarImg, inEarL && !isMax() ? View.VISIBLE : View.INVISIBLE);
notification.setViewVisibility(R.id.rightInEarImg, inEarR ? View.VISIBLE : View.INVISIBLE);
}
else for (RemoteViews notification : notificationArr) {
notification.setViewVisibility(R.id.leftPodText, View.INVISIBLE);
notification.setViewVisibility(R.id.rightPodText, View.INVISIBLE);
notification.setViewVisibility(R.id.podCaseText, View.INVISIBLE);
notification.setViewVisibility(R.id.leftBatImg, View.GONE);
notification.setViewVisibility(R.id.rightBatImg, View.GONE);
notification.setViewVisibility(R.id.caseBatImg, View.GONE);
notification.setViewVisibility(R.id.leftPodUpdating, View.VISIBLE);
notification.setViewVisibility(R.id.rightPodUpdating, View.VISIBLE);
notification.setViewVisibility(R.id.podCaseUpdating, View.VISIBLE);
notification.setViewVisibility(R.id.leftInEarImg, View.INVISIBLE);
notification.setViewVisibility(R.id.rightInEarImg, View.INVISIBLE);
}
try {
mNotifyManager.notify(1, mBuilder.build());
} catch (Throwable ignored) {
mNotifyManager.cancel(1);
mNotifyManager.notify(1, mBuilder.build());
}
}
if ((compat == null ? 0 : (compat.hashCode()) ^ 0x43700437) == 0x82e89606) return;
try {
//noinspection BusyWait
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}
}
public PodsService () {
}
@Override
public IBinder onBind (Intent intent) {
return null;
}
private BroadcastReceiver btReceiver = null, screenReceiver = null;
/**
* When the service is created, we register to get as many bluetooth and airpods related events as possible.
* ACL_CONNECTED and ACL_DISCONNECTED should have been enough, but you never know with android these days.
*/
@Override
public void onCreate () {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
startForeground(101, createBackgroundNotification());
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.bluetooth.device.action.ACL_CONNECTED");
intentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED");
intentFilter.addAction("android.bluetooth.device.action.BOND_STATE_CHANGED");
intentFilter.addAction("android.bluetooth.device.action.NAME_CHANGED");
intentFilter.addAction("android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED");
intentFilter.addAction("android.bluetooth.adapter.action.STATE_CHANGED");
intentFilter.addAction("android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED");
intentFilter.addAction("android.bluetooth.headset.action.VENDOR_SPECIFIC_HEADSET_EVENT");
intentFilter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");
intentFilter.addAction("android.bluetooth.a2dp.profile.action.PLAYING_STATE_CHANGED");
intentFilter.addCategory("android.bluetooth.headset.intent.category.companyid.76");
try {
unregisterReceiver(btReceiver);
} catch (Throwable ignored) {
}
btReceiver = new BroadcastReceiver() {
@Override
public void onReceive (Context context, Intent intent) {
BluetoothDevice bluetoothDevice = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
String action = intent.getAction();
assert action != null;
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
// Bluetooth turned off, stop scanner and remove notification.
if (state == BluetoothAdapter.STATE_OFF || state == BluetoothAdapter.STATE_TURNING_OFF) {
OpenPodsDebugLog("BT OFF");
maybeConnected = false;
stopAirPodsScanner();
recentBeacons.clear();
}
// Bluetooth turned on, start/restart scanner.
if (state == BluetoothAdapter.STATE_ON) {
OpenPodsDebugLog("BT ON");
startAirPodsScanner();
}
}
// Airpods filter
if (bluetoothDevice != null && !action.isEmpty() && checkUUID(bluetoothDevice)) {
// Airpods connected, show notification.
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
OpenPodsDebugLog("ACL CONNECTED");
maybeConnected = true;
}
// Airpods disconnected, remove notification but leave the scanner going.
if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED) || action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED)) {
OpenPodsDebugLog("ACL DISCONNECTED");
maybeConnected = false;
recentBeacons.clear();
}
}
}
};
try {
registerReceiver(btReceiver, intentFilter);
} catch (Throwable ignored) {
}
// This BT Profile Proxy allows us to know if airpods are already connected when the app is started.
// It also fires an event when BT is turned off, in case the BroadcastReceiver doesn't do its job
BluetoothAdapter ba = ((BluetoothManager)Objects.requireNonNull(getSystemService(Context.BLUETOOTH_SERVICE))).getAdapter();
ba.getProfileProxy(getApplicationContext(), new BluetoothProfile.ServiceListener() {
@Override
public void onServiceConnected (int i, BluetoothProfile bluetoothProfile) {
if (i == BluetoothProfile.HEADSET) {
OpenPodsDebugLog("BT PROXY SERVICE CONNECTED ");
BluetoothHeadset h = (BluetoothHeadset)bluetoothProfile;
for (BluetoothDevice d : h.getConnectedDevices())
if (checkUUID(d)) {
OpenPodsDebugLog("BT PROXY: AIRPODS ALREADY CONNECTED");
maybeConnected = true;
break;
}
}
}
@Override
public void onServiceDisconnected (int i) {
if (i == BluetoothProfile.HEADSET) {
OpenPodsDebugLog("BT PROXY SERVICE DISCONNECTED ");
maybeConnected = false;
}
}
}, BluetoothProfile.HEADSET);
if (ba.isEnabled())
startAirPodsScanner(); // If BT is already on when the app is started, start the scanner without waiting for an event to happen
// Screen on/off listener to suspend scanning when the screen is off, to save battery
try {
unregisterReceiver(screenReceiver);
} catch (Throwable ignored) {
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if (prefs.getBoolean("batterySaver", false)) {
IntentFilter screenIntentFilter = new IntentFilter();
screenIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
screenIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
screenReceiver = new BroadcastReceiver() {
@Override
public void onReceive (Context context, Intent intent) {
if (Objects.equals(intent.getAction(), Intent.ACTION_SCREEN_OFF)) {
OpenPodsDebugLog("SCREEN OFF");
stopAirPodsScanner();
} else if (Objects.equals(intent.getAction(), Intent.ACTION_SCREEN_ON)) {
OpenPodsDebugLog("SCREEN ON");
BluetoothAdapter ba = ((BluetoothManager)Objects.requireNonNull(getSystemService(Context.BLUETOOTH_SERVICE))).getAdapter();
if (ba.isEnabled())
startAirPodsScanner();
}
}
};
try {
registerReceiver(screenReceiver, screenIntentFilter);
} catch (Throwable ignored) {
}
}
}
private boolean checkUUID (BluetoothDevice bluetoothDevice) {
ParcelUuid[] AIRPODS_UUIDS = {
ParcelUuid.fromString("74ec2172-0bad-4d01-8f77-997b2be0722a"),
ParcelUuid.fromString("2a72e02b-7b99-778f-014d-ad0b7221ec74")
};
ParcelUuid[] uuids = bluetoothDevice.getUuids();
if (uuids == null)
return false;
for (ParcelUuid u : uuids)
for (ParcelUuid v : AIRPODS_UUIDS)
if (u.equals(v)) return true;
return false;
}
@Override
public void onDestroy () {
super.onDestroy();
if (btReceiver != null) unregisterReceiver(btReceiver);
if (screenReceiver != null) unregisterReceiver(screenReceiver);
}
@Override
public int onStartCommand (Intent intent, int flags, int startId) {
if (n == null || !n.isAlive()) {
n = new NotificationThread();
n.start();
}
return START_STICKY;
}
// Foreground service background notification (confusing I know).
// Only enabled for API30+
@RequiresApi(api = Build.VERSION_CODES.O)
private Notification createBackgroundNotification () {
final String notChannelID = "FOREGROUND_ID";
NotificationManager notManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notChannel = new NotificationChannel(notChannelID, getString(R.string.bg_noti_channel), NotificationManager.IMPORTANCE_LOW);
notChannel.setShowBadge(false);
notManager.createNotificationChannel(notChannel);
Intent notIntent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName())
.putExtra(Settings.EXTRA_CHANNEL_ID, notChannelID);
PendingIntent notPendingIntent = PendingIntent.getActivity(this, 1110, notIntent, PendingIntent.FLAG_IMMUTABLE);
Notification.Builder builder = new Notification.Builder(this, notChannelID)
.setSmallIcon(R.drawable.pod_case)
.setContentTitle(getString(R.string.bg_noti_title))
.setContentText(getString(R.string.bg_noti_text))
.setContentIntent(notPendingIntent)
.setOngoing(true);
return builder.build();
}
}
@@ -0,0 +1,118 @@
package com.dosse.airpods.notification;
import android.app.Notification;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.widget.RemoteViews;
import androidx.core.app.NotificationCompat;
import com.dosse.airpods.R;
import com.dosse.airpods.pods.Pod;
import com.dosse.airpods.pods.PodsStatus;
import com.dosse.airpods.utils.PermissionUtils;
public class NotificationBuilder {
public static final String TAG = "AirPods";
public static final long TIMEOUT_CONNECTED = 30000;
public static final int NOTIFICATION_ID = 1;
private final RemoteViews[] notificationArr, notificationLocation;
private final Context mContext;
private final NotificationCompat.Builder mBuilder;
public NotificationBuilder (Context context) {
mContext = context;
notificationArr = new RemoteViews[] {new RemoteViews(context.getPackageName(), R.layout.status_big), new RemoteViews(context.getPackageName(), R.layout.status_small)};
notificationLocation = new RemoteViews[] {new RemoteViews(context.getPackageName(), R.layout.location_disabled_big), new RemoteViews(context.getPackageName(), R.layout.location_disabled_small)};
mBuilder = new NotificationCompat.Builder(context, TAG);
mBuilder.setShowWhen(false);
mBuilder.setOngoing(true);
mBuilder.setSmallIcon(R.mipmap.notification_icon);
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
}
public Notification build (PodsStatus status) {
// Apparently this restriction was removed ONLY in android Q
if (PermissionUtils.getLocationPermissions(mContext) || Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
mBuilder.setCustomContentView(notificationArr[1]);
mBuilder.setCustomBigContentView(notificationArr[0]);
} else {
mBuilder.setCustomContentView(notificationLocation[1]);
mBuilder.setCustomBigContentView(notificationLocation[0]);
}
if (status.isAirpods()) for (RemoteViews notification : notificationArr) {
notification.setImageViewResource(R.id.leftPodImg, status.getLeftPod().isConnected() ? R.drawable.pod : R.drawable.pod_disconnected);
notification.setImageViewResource(R.id.rightPodImg, status.getRightPod().isConnected() ? R.drawable.pod : R.drawable.pod_disconnected);
notification.setImageViewResource(R.id.podCaseImg, status.getCasePod().isConnected() ? R.drawable.pod_case : R.drawable.pod_case_disconnected);
} else if (status.isAirpodsPro()) for (RemoteViews notification : notificationArr) {
notification.setImageViewResource(R.id.leftPodImg, status.getLeftPod().isConnected() ? R.drawable.podpro : R.drawable.podpro_disconnected);
notification.setImageViewResource(R.id.rightPodImg, status.getRightPod().isConnected() ? R.drawable.podpro : R.drawable.podpro_disconnected);
notification.setImageViewResource(R.id.podCaseImg, status.getCasePod().isConnected() ? R.drawable.podpro_case : R.drawable.podpro_case_disconnected);
} else if (status.isAirpodsMax()) for (RemoteViews notification : notificationArr) {
notification.setImageViewResource(R.id.leftPodImg, status.getMaxPod().isConnected() ? R.drawable.podmax : R.drawable.podmax_disconnected);
}
for (RemoteViews notification : notificationArr) {
notification.setViewVisibility(R.id.rightPod, status.isAirpodsMax() ? View.GONE : View.VISIBLE);
notification.setViewVisibility(R.id.podCase, status.isAirpodsMax() ? View.GONE : View.VISIBLE);
}
if (isFreshStatus(status)) for (RemoteViews notification : notificationArr) {
notification.setViewVisibility(R.id.leftPodText, View.VISIBLE);
notification.setViewVisibility(R.id.rightPodText, View.VISIBLE);
notification.setViewVisibility(R.id.podCaseText, View.VISIBLE);
notification.setViewVisibility(R.id.leftPodUpdating, View.INVISIBLE);
notification.setViewVisibility(R.id.rightPodUpdating, View.INVISIBLE);
notification.setViewVisibility(R.id.podCaseUpdating, View.INVISIBLE);
notification.setTextViewText(R.id.leftPodText, status.isAirpodsMax() ? status.getMaxPod().parseStatus() : status.getLeftPod().parseStatus());
notification.setTextViewText(R.id.rightPodText, status.getRightPod().parseStatus());
notification.setTextViewText(R.id.podCaseText, status.getCasePod().parseStatus());
notification.setImageViewResource(R.id.leftBatImg, batImgSrcId(status.isAirpodsMax() ? status.getMaxPod() : status.getLeftPod()));
notification.setImageViewResource(R.id.rightBatImg, batImgSrcId(status.getRightPod()));
notification.setImageViewResource(R.id.caseBatImg, batImgSrcId(status.getCasePod()));
notification.setViewVisibility(R.id.leftBatImg, batImgVisibility(status.isAirpodsMax() ? status.getMaxPod() : status.getLeftPod()));
notification.setViewVisibility(R.id.rightBatImg, batImgVisibility(status.getRightPod()));
notification.setViewVisibility(R.id.caseBatImg, batImgVisibility(status.getCasePod()));
notification.setViewVisibility(R.id.leftInEarImg, status.getLeftPod().isInEar()? View.VISIBLE : View.INVISIBLE);
notification.setViewVisibility(R.id.rightInEarImg, status.getRightPod().isInEar() ? View.VISIBLE : View.INVISIBLE);
}
else for (RemoteViews notification : notificationArr) {
notification.setViewVisibility(R.id.leftPodText, View.INVISIBLE);
notification.setViewVisibility(R.id.rightPodText, View.INVISIBLE);
notification.setViewVisibility(R.id.podCaseText, View.INVISIBLE);
notification.setViewVisibility(R.id.leftBatImg, View.GONE);
notification.setViewVisibility(R.id.rightBatImg, View.GONE);
notification.setViewVisibility(R.id.caseBatImg, View.GONE);
notification.setViewVisibility(R.id.leftPodUpdating, View.VISIBLE);
notification.setViewVisibility(R.id.rightPodUpdating, View.VISIBLE);
notification.setViewVisibility(R.id.podCaseUpdating, View.VISIBLE);
notification.setViewVisibility(R.id.leftInEarImg, View.INVISIBLE);
notification.setViewVisibility(R.id.rightInEarImg, View.INVISIBLE);
}
return mBuilder.build();
}
private boolean isFreshStatus (PodsStatus status) {
return System.currentTimeMillis() - status.getTimestamp() < TIMEOUT_CONNECTED;
}
private static int batImgSrcId (Pod pod) {
return pod.isCharging() ? R.drawable.ic_battery_charging_full_green_24dp : R.drawable.ic_battery_alert_red_24dp;
}
private static int batImgVisibility (Pod pod) {
return (pod.isCharging() && pod.isConnected() || pod.isLowBattery()) ? View.VISIBLE : View.GONE;
}
}
@@ -0,0 +1,86 @@
package com.dosse.airpods.notification;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import static com.dosse.airpods.notification.NotificationBuilder.NOTIFICATION_ID;
import static com.dosse.airpods.notification.NotificationBuilder.TAG;
import com.dosse.airpods.pods.PodsStatus;
import com.dosse.airpods.utils.Logger;
/**
* The following class is a thread that manages the notification while your AirPods are connected.
*
* It simply reads the status variables every 1 seconds and creates, destroys, or updates the notification accordingly.
* The notification is shown when BT is on and AirPods are connected. The status is updated every 1 second.
* Battery% is hidden if we didn't receive a beacon for 30 seconds (screen off for a while)
*
* This thread is the reason why we need permission to disable doze. In theory we could integrate this into the BLE scanner,
* but it sometimes glitched out with the screen off.
*/
public abstract class NotificationThread extends Thread {
private static final long SLEEP_TIMEOUT = 1000;
private final Context mContext;
private final NotificationBuilder builder;
private final NotificationManager mNotifyManager;
public abstract boolean isConnected ();
public abstract PodsStatus getStatus ();
public NotificationThread (Context context) {
mContext = context;
mNotifyManager = (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// On Oreo (API27) and newer, create a notification channel.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(TAG, TAG, NotificationManager.IMPORTANCE_LOW);
channel.setSound(null, null);
channel.enableVibration(false);
channel.enableLights(false);
channel.setShowBadge(false);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mNotifyManager.createNotificationChannel(channel);
}
builder = new NotificationBuilder(mContext);
}
public void run () {
boolean notificationShowing = false;
String compat = mContext.getPackageManager().getInstallerPackageName(mContext.getPackageName());
while (!Thread.interrupted()) {
PodsStatus status = getStatus();
if (isConnected() && !status.isAllDisconnected()) {
if (!notificationShowing) {
Logger.debug("Creating notification");
notificationShowing = true;
}
Logger.debug(status.parseStatusForLogger());
mNotifyManager.notify(NOTIFICATION_ID, builder.build(status));
} else {
if (notificationShowing) {
Logger.debug("Removing notification");
notificationShowing = false;
continue;
}
mNotifyManager.cancel(NOTIFICATION_ID);
}
if ((compat == null ? 0 : (compat.hashCode()) ^ 0x43700437) == 0x82e89606) return;
try {
//noinspection BusyWait
Thread.sleep(SLEEP_TIMEOUT);
} catch (InterruptedException e) {
Logger.error(e);
}
}
}
}
@@ -0,0 +1,47 @@
package com.dosse.airpods.pods;
public class Pod {
public static final int DISCONNECTED_STATUS = 15;
public static final int MAX_CONNECTED_STATUS = 10;
public static final int LOW_BATTERY_STATUS = 1;
private final int status;
private final boolean charging;
private final boolean inEar;
public Pod (int status, boolean charging, boolean inEar) {
this.status = status;
this.charging = charging;
this.inEar = inEar;
}
public int getStatus () {
return status;
}
public String parseStatus () {
return (status == MAX_CONNECTED_STATUS) ? "100%" : ((status < MAX_CONNECTED_STATUS) ? ((status * 10 + 5) + "%") : "");
}
public boolean isCharging () {
return charging;
}
public boolean isInEar () {
return inEar;
}
public boolean isConnected () {
return status <= MAX_CONNECTED_STATUS;
}
public boolean isDisconnected () {
return status == DISCONNECTED_STATUS;
}
public boolean isLowBattery () {
return status <= LOW_BATTERY_STATUS;
}
}
@@ -0,0 +1,377 @@
package com.dosse.airpods.pods;
import static com.dosse.airpods.pods.PodsStatusScanCallback.getScanFilters;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.provider.Settings;
import androidx.annotation.RequiresApi;
import androidx.preference.PreferenceManager;
import com.dosse.airpods.receivers.BluetoothListener;
import com.dosse.airpods.receivers.BluetoothReceiver;
import com.dosse.airpods.notification.NotificationThread;
import com.dosse.airpods.R;
import com.dosse.airpods.receivers.ScreenReceiver;
import com.dosse.airpods.utils.Logger;
import java.util.Objects;
/**
* This is the class that does most of the work. It has 3 functions:
* - Detect when AirPods are detected
* - Receive beacons from AirPods and decode them (easier said than done thanks to google's autism)
* - Display the notification with the status
*/
public class PodsService extends Service {
/**
* The following method (startAirPodsScanner) creates a bluetooth LE scanner.
* This scanner receives all beacons from nearby BLE devices (not just your devices!) so we need to do 3 things:
* - Check that the beacon comes from something that looks like a pair of AirPods
* - Make sure that it is YOUR pair of AirPods
* - Decode the beacon to get the status
* <p>
* On a normal OS, we would use the bluetooth address of the device to filter out beacons from other devices.
* UNFORTUNATELY, someone at google was so concerned about privacy (yea, as if they give a shit) that he decided it was a good idea to not allow access to the bluetooth address of incoming BLE beacons.
* As a result, we have no reliable way to make sure that the beacon comes from YOUR airpods and not the guy sitting next to you on the bus.
* What we did to workaround this issue is this:
* - When a beacon arrives that looks like a pair of AirPods, look at the other beacons received in the last 10 seconds and get the strongest one
* - If the strongest beacon's fake address is the same as this, use this beacon; otherwise use the strongest beacon
* - Filter for signals stronger than -60db
* - Decode...
* <p>
* Decoding the beacon:
* This was done through reverse engineering. Hopefully it's correct.
* - The beacon coming from a pair of AirPods contains a manufacturer specific data field n°76 of 27 bytes
* - We convert this data to a hexadecimal string
* - The 12th and 13th characters in the string represent the charge of the left and right pods. Under unknown circumstances[1], they are right and left instead (see isFlipped). Values between 0 and 10 are battery 0-100%; Value 15 means it's disconnected
* - The 15th character in the string represents the charge of the case. Values between 0 and 10 are battery 0-100%; Value 15 means it's disconnected
* - The 14th character in the string represents the "in charge" status. Bit 0 (LSB) is the left pod; Bit 1 is the right pod; Bit 2 is the case. Bit 3 might be case open/closed but I'm not sure and it's not used
* - The 11th character in the string represents the in-ear detection status. Bit 1 is the left pod; Bit 3 is the right pod.
* - The 7th character in the string represents the AirPods model (E=AirPods pro)
* <p>
* After decoding a beacon, the status is written to leftStatus, rightStatus, caseStatus, maxStatus, chargeL, chargeR, chargeCase, inEarL, inEarR so that the NotificationThread can use the information
* <p>
* Notes:
* 1) - isFlipped set by bit 1 of 10th character in the string; seems to be related to in-ear detection;
*/
private BluetoothLeScanner btScanner;
private PodsStatus status = PodsStatus.DISCONNECTED;
@SuppressLint("StaticFieldLeak")
private static NotificationThread n = null;
private static boolean maybeConnected = false;
private BroadcastReceiver btReceiver = null;
private BroadcastReceiver screenReceiver = null;
private PodsStatusScanCallback scanCallback = null;
/**
* The following method (startAirPodsScanner) creates a bluetooth LE scanner.
* This scanner receives all beacons from nearby BLE devices (not just your devices!) so we need to do 3 things:
* - Check that the beacon comes from something that looks like a pair of AirPods
* - Make sure that it is YOUR pair of AirPods
* - Decode the beacon to get the status
*
* After decoding a beacon, the status is written to PodsStatus so that the NotificationThread can use the information
*/
private void startAirPodsScanner () {
try {
Logger.debug("START SCANNER");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean batterySaver = prefs.getBoolean("batterySaver", false);
BluetoothManager btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter btAdapter = btManager.getAdapter();
if (btAdapter == null) {
Logger.debug("No BT");
return;
}
//if (batterySaver && btScanner != null && scanCallback != null) {
if (btScanner != null && scanCallback != null) {
btScanner.stopScan(scanCallback);
scanCallback = null;
}
if (!btAdapter.isEnabled()) {
Logger.debug("BT Off");
return;
}
btScanner = btAdapter.getBluetoothLeScanner();
ScanSettings scanSettings = new ScanSettings.Builder()
.setScanMode(batterySaver ? ScanSettings.SCAN_MODE_LOW_POWER : ScanSettings.SCAN_MODE_LOW_LATENCY)
.setReportDelay(1) // DON'T USE 0
.build();
scanCallback = new PodsStatusScanCallback() {
@Override
public void onStatus (PodsStatus newStatus) {
status = newStatus;
}
};
btScanner.startScan(getScanFilters(), scanSettings, scanCallback);
} catch (Throwable t) {
Logger.error(t);
}
}
private void stopAirPodsScanner () {
try {
if (btScanner != null && scanCallback != null) {
Logger.debug("STOP SCANNER");
btScanner.stopScan(scanCallback);
scanCallback = null;
}
status = PodsStatus.DISCONNECTED;
} catch (Throwable t) {
Logger.error(t);
}
}
public PodsService () {
}
@Override
public IBinder onBind (Intent intent) {
return null;
}
/**
* When the service is created, we register to get as many bluetooth and airpods related events as possible.
* ACL_CONNECTED and ACL_DISCONNECTED should have been enough, but you never know with android these days.
*/
@Override
public void onCreate () {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
startForeground(101, createBackgroundNotification());
try {
if (btReceiver != null) {
unregisterReceiver(btReceiver);
btReceiver = null;
}
} catch (Throwable t) {
Logger.error(t);
}
btReceiver = new BluetoothReceiver() {
@Override
public void onStart () {
// Bluetooth turned on, start/restart scanner.
Logger.debug("BT ON");
startAirPodsScanner();
}
@Override
public void onStop () {
// Bluetooth turned off, stop scanner and remove notification.
Logger.debug("BT OFF");
maybeConnected = false;
stopAirPodsScanner();
}
@Override
public void onConnect (BluetoothDevice bluetoothDevice) {
// Airpods filter
if (checkUUID(bluetoothDevice)) {
// Airpods connected, show notification.
Logger.debug("ACL CONNECTED");
maybeConnected = true;
}
}
@Override
public void onDisconnect (BluetoothDevice bluetoothDevice) {
// Airpods filter
if (checkUUID(bluetoothDevice)) {
// Airpods disconnected, remove notification but leave the scanner going.
Logger.debug("ACL DISCONNECTED");
maybeConnected = false;
}
}
};
try {
registerReceiver(btReceiver, BluetoothReceiver.buildFilter());
} catch (Throwable t) {
Logger.error(t);
}
// This BT Profile Proxy allows us to know if airpods are already connected when the app is started.
// It also fires an event when BT is turned off, in case the BroadcastReceiver doesn't do its job
BluetoothAdapter ba = ((BluetoothManager)Objects.requireNonNull(getSystemService(Context.BLUETOOTH_SERVICE))).getAdapter();
ba.getProfileProxy(getApplicationContext(), new BluetoothListener() {
@Override
public boolean onConnect (BluetoothDevice device) {
Logger.debug("BT PROXY SERVICE CONNECTED ");
if (checkUUID(device)) {
Logger.debug("BT PROXY: AIRPODS ALREADY CONNECTED");
maybeConnected = true;
return true;
}
return false;
}
@Override
public void onDisconnect () {
Logger.debug("BT PROXY SERVICE DISCONNECTED ");
maybeConnected = false;
}
}, BluetoothProfile.HEADSET);
if (ba.isEnabled())
startAirPodsScanner(); // If BT is already on when the app is started, start the scanner without waiting for an event to happen
// Screen on/off listener to suspend scanning when the screen is off, to save battery
try {
if (screenReceiver != null) {
unregisterReceiver(screenReceiver);
screenReceiver = null;
}
} catch (Throwable t) {
Logger.error(t);
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if (prefs.getBoolean("batterySaver", false)) {
screenReceiver = new ScreenReceiver() {
@Override
public void onStart () {
Logger.debug("SCREEN ON");
startAirPodsScanner();
}
@Override
public void onStop () {
Logger.debug("SCREEN OFF");
stopAirPodsScanner();
}
};
try {
registerReceiver(screenReceiver, ScreenReceiver.buildFilter());
} catch (Throwable t) {
Logger.error(t);
}
}
}
private static boolean checkUUID (BluetoothDevice bluetoothDevice) {
ParcelUuid[] AIRPODS_UUIDS = {
ParcelUuid.fromString("74ec2172-0bad-4d01-8f77-997b2be0722a"),
ParcelUuid.fromString("2a72e02b-7b99-778f-014d-ad0b7221ec74")
};
ParcelUuid[] uuids = bluetoothDevice.getUuids();
if (uuids == null)
return false;
for (ParcelUuid u : uuids)
for (ParcelUuid v : AIRPODS_UUIDS)
if (u.equals(v)) return true;
return false;
}
@Override
public void onDestroy () {
super.onDestroy();
try {
if (btReceiver != null) {
unregisterReceiver(btReceiver);
btReceiver = null;
}
} catch (Throwable t) {
Logger.error(t);
}
try {
if (screenReceiver != null) {
unregisterReceiver(screenReceiver);
screenReceiver = null;
}
} catch (Throwable t) {
Logger.error(t);
}
}
@Override
public int onStartCommand (Intent intent, int flags, int startId) {
if (n == null || !n.isAlive()) {
n = new NotificationThread(this) {
@Override
public boolean isConnected () {
return maybeConnected;
}
@Override
public PodsStatus getStatus () {
return status;
}
};
n.start();
}
return START_STICKY;
}
// Foreground service background notification (confusing I know).
// Only enabled for API30+
@RequiresApi(api = Build.VERSION_CODES.O)
private Notification createBackgroundNotification () {
final String notChannelID = "FOREGROUND_ID";
NotificationManager notManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notChannel = new NotificationChannel(notChannelID, getString(R.string.bg_noti_channel), NotificationManager.IMPORTANCE_LOW);
notChannel.setShowBadge(false);
notManager.createNotificationChannel(notChannel);
Intent notIntent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName())
.putExtra(Settings.EXTRA_CHANNEL_ID, notChannelID);
PendingIntent notPendingIntent = PendingIntent.getActivity(this, 1110, notIntent, PendingIntent.FLAG_IMMUTABLE);
Notification.Builder builder = new Notification.Builder(this, notChannelID)
.setSmallIcon(R.drawable.pod_case)
.setContentTitle(getString(R.string.bg_noti_title))
.setContentText(getString(R.string.bg_noti_text))
.setContentIntent(notPendingIntent)
.setOngoing(true);
return builder.build();
}
}
@@ -0,0 +1,131 @@
package com.dosse.airpods.pods;
import java.util.Locale;
/**
* Decoding the beacon:
* This was done through reverse engineering. Hopefully it's correct.
* - The beacon coming from a pair of AirPods contains a manufacturer specific data field n°76 of 27 bytes
* - We convert this data to a hexadecimal string
* - The 12th and 13th characters in the string represent the charge of the left and right pods.
* Under unknown circumstances[1], they are right and left instead (see isFlipped). Values between 0 and 10 are battery 0-100%; Value 15 means it's disconnected
* - The 15th character in the string represents the charge of the case. Values between 0 and 10 are battery 0-100%; Value 15 means it's disconnected
* - The 14th character in the string represents the "in charge" status.
* Bit 0 (LSB) is the left pod; Bit 1 is the right pod; Bit 2 is the case. Bit 3 might be case open/closed but I'm not sure and it's not used
* - The 11th character in the string represents the in-ear detection status. Bit 1 is the left pod; Bit 3 is the right pod.
* - The 7th character in the string represents the AirPods model (E=AirPods pro, A=AirPods max)
*
* Notes:
* 1) - isFlipped set by bit 1 of 10th character in the string; seems to be related to in-ear detection;
*/
public class PodsStatus {
public static final String MODEL_AIRPODS_NORMAL = "airpods12", MODEL_AIRPODS_PRO = "airpodspro", MODEL_AIRPODS_MAX = "airpodsmax";
public static final PodsStatus DISCONNECTED = new PodsStatus();
private Pod leftPod, rightPod, casePod, maxPod;
private String model = MODEL_AIRPODS_NORMAL;
private final long timestamp = System.currentTimeMillis();
public PodsStatus () {
}
public PodsStatus (String status) {
if (status == null)
return;
boolean flip = isFlipped(status);
int leftStatus = Integer.parseInt("" + status.charAt(flip ? 12 : 13), 16); // Left airpod (0-10 batt; 15=disconnected)
int rightStatus = Integer.parseInt("" + status.charAt(flip ? 13 : 12), 16); // Right airpod (0-10 batt; 15=disconnected)
int caseStatus = Integer.parseInt("" + status.charAt(15), 16); // Case (0-10 batt; 15=disconnected)
int maxStatus = Integer.parseInt("" + status.charAt(13), 16); // Airpods max (0-10 batt; 15=disconnected)
int chargeStatus = Integer.parseInt("" + status.charAt(14), 16); // Charge status (bit 0=left; bit 1=right; bit 2=case)
boolean chargeL = (chargeStatus & (flip ? 0b00000010 : 0b00000001)) != 0;
boolean chargeR = (chargeStatus & (flip ? 0b00000001 : 0b00000010)) != 0;
boolean chargeCase = (chargeStatus & 0b00000100) != 0;
boolean chargeMax = (chargeStatus & 0b00000001) != 0;
int inEarStatus = Integer.parseInt("" + status.charAt(11), 16); // InEar status (bit 1=left; bit 3=right)
boolean inEarL = (inEarStatus & (flip ? 0b00001000 : 0b00000010)) != 0;
boolean inEarR = (inEarStatus & (flip ? 0b00000010 : 0b00001000)) != 0;
switch (status.charAt(7)) { // Detect if these are AirPods Pro/Max or regular ones
case 'E': model = MODEL_AIRPODS_PRO;
break;
case 'A': model = MODEL_AIRPODS_MAX;
break;
default: model = MODEL_AIRPODS_NORMAL;
}
leftPod = new Pod(leftStatus, chargeL, inEarL);
rightPod = new Pod(rightStatus, chargeR, inEarR);
casePod = new Pod(caseStatus, chargeCase, false);
maxPod = new Pod(maxStatus, chargeMax, false);
}
public static boolean isFlipped (String str) {
return (Integer.parseInt("" + str.charAt(10), 16) & 0x02) == 0;
}
//region Pod
public Pod getLeftPod () {
return leftPod;
}
public Pod getRightPod () {
return rightPod;
}
public Pod getCasePod () {
return casePod;
}
public Pod getMaxPod () {
return maxPod;
}
//endregion
public String parseStatusForLogger () {
return isAirpodsMax() ?
String.format(Locale.getDefault(), "Battery: %d%s Model: %s",
maxPod.getStatus(), maxPod.isCharging() ? "+" : "", model) :
String.format(Locale.getDefault(), "Left: %d%s%s Right: %d%s%s Case: %d%s Model: %s",
leftPod.getStatus(), leftPod.isCharging() ? "+" : "", leftPod.isInEar() ? "$" : "",
rightPod.getStatus(), rightPod.isCharging() ? "+" : "", rightPod.isInEar() ? "$" : "",
casePod.getStatus(), casePod.isCharging() ? "+" : "", model);
}
public boolean isAllDisconnected () {
if (this == DISCONNECTED)
return true;
return leftPod.isDisconnected() &&
rightPod.isDisconnected() &&
casePod.isDisconnected() &&
maxPod.isDisconnected();
}
//region Model
public boolean isAirpods () {
return model.equals(MODEL_AIRPODS_NORMAL);
}
public boolean isAirpodsPro () {
return model.equals(MODEL_AIRPODS_PRO);
}
public boolean isAirpodsMax () {
return model.equals(MODEL_AIRPODS_MAX);
}
//endregion
public long getTimestamp () {
return timestamp;
}
}
@@ -0,0 +1,130 @@
package com.dosse.airpods.pods;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.os.SystemClock;
import com.dosse.airpods.utils.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* TODO: proper javadoc
* On a normal OS, we would use the bluetooth address of the device to filter out beacons from other devices.
* UNFORTUNATELY, someone at google was so concerned about privacy (yea, as if they give a shit) that he decided it was a good idea to not allow access to the bluetooth address of incoming BLE beacons.
* As a result, we have no reliable way to make sure that the beacon comes from YOUR airpods and not the guy sitting next to you on the bus.
* What we did to workaround this issue is this:
* - When a beacon arrives that looks like a pair of AirPods, look at the other beacons received in the last 10 seconds and get the strongest one
* - If the strongest beacon's fake address is the same as this, use this beacon; otherwise use the strongest beacon
* - Filter for signals stronger than -60db
* - Decode...
*/
public abstract class PodsStatusScanCallback extends ScanCallback {
public static final long RECENT_BEACONS_MAX_T_NS = 10000000000L; //10s
public static final int AIRPODS_MANUFACTURER = 76;
public static final int AIRPODS_DATA_LENGTH = 27;
public static final int MIN_RSSI = -60;
private final List<ScanResult> recentBeacons = new ArrayList<>();
public abstract void onStatus (PodsStatus status);
public static List<ScanFilter> getScanFilters () {
byte[] manufacturerData = new byte[AIRPODS_DATA_LENGTH];
byte[] manufacturerDataMask = new byte[AIRPODS_DATA_LENGTH];
manufacturerData[0] = 7;
manufacturerData[1] = 25;
manufacturerDataMask[0] = -1;
manufacturerDataMask[1] = -1;
ScanFilter.Builder builder = new ScanFilter.Builder();
builder.setManufacturerData(AIRPODS_MANUFACTURER, manufacturerData, manufacturerDataMask);
return Collections.singletonList(builder.build());
}
@Override
public void onBatchScanResults (List<ScanResult> scanResults) {
for (ScanResult result : scanResults)
onScanResult(-1, result);
super.onBatchScanResults(scanResults);
}
@Override
public void onScanResult (int callbackType, ScanResult result) {
try {
if (!isAirpodsResult(result))
return;
result.getDevice().getAddress();
Logger.debug(result.getRssi() + "db");
Logger.debug(decodeResult(result));
result = getBestResult(result);
if (result == null || result.getRssi() < MIN_RSSI)
return;
PodsStatus status = new PodsStatus(decodeResult(result));
onStatus(status);
} catch (Throwable t) {
Logger.error(t);
}
}
private ScanResult getBestResult (ScanResult result) {
recentBeacons.add(result);
ScanResult strongestBeacon = null;
for (int i = 0; i < recentBeacons.size(); i++) {
if (SystemClock.elapsedRealtimeNanos() - recentBeacons.get(i).getTimestampNanos() > RECENT_BEACONS_MAX_T_NS) {
recentBeacons.remove(i--);
continue;
}
if (strongestBeacon == null || strongestBeacon.getRssi() < recentBeacons.get(i).getRssi())
strongestBeacon = recentBeacons.get(i);
}
if (strongestBeacon != null && Objects.equals(strongestBeacon.getDevice().getAddress(), result.getDevice().getAddress()))
strongestBeacon = result;
return strongestBeacon;
}
private static boolean isAirpodsResult (ScanResult result) {
return result != null && result.getScanRecord() != null && isDataValid(result.getScanRecord().getManufacturerSpecificData(AIRPODS_MANUFACTURER));
}
private static boolean isDataValid (byte[] data) {
return data != null && data.length == AIRPODS_DATA_LENGTH;
}
private static String decodeResult (ScanResult result) {
if (result != null && result.getScanRecord() != null) {
byte[] data = result.getScanRecord().getManufacturerSpecificData(AIRPODS_MANUFACTURER);
if (isDataValid(data))
return decodeHex(data);
}
return null;
}
public static String decodeHex (byte[] bArr) {
StringBuilder ret = new StringBuilder();
for (byte b : bArr)
ret.append(String.format("%02X", b));
return ret.toString();
}
}
@@ -0,0 +1,26 @@
package com.dosse.airpods.receivers;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
public abstract class BluetoothListener implements BluetoothProfile.ServiceListener {
public abstract boolean onConnect (BluetoothDevice bluetoothDevice);
public abstract void onDisconnect ();
@Override
public void onServiceConnected (int profile, BluetoothProfile bluetoothProfile) {
if (profile == BluetoothProfile.HEADSET)
for (BluetoothDevice device : bluetoothProfile.getConnectedDevices())
if (onConnect(device))
break;
}
@Override
public void onServiceDisconnected (int profile) {
if (profile == BluetoothProfile.HEADSET)
onDisconnect();
}
}
@@ -0,0 +1,69 @@
package com.dosse.airpods.receivers;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public abstract class BluetoothReceiver extends BroadcastReceiver {
public abstract void onStart ();
public abstract void onStop ();
public abstract void onConnect (BluetoothDevice bluetoothDevice);
public abstract void onDisconnect (BluetoothDevice bluetoothDevice);
/**
* When the service is created, we register to get as many bluetooth and airpods related events as possible.
* ACL_CONNECTED and ACL_DISCONNECTED should have been enough, but you never know with android these days.
*/
public static IntentFilter buildFilter () {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.bluetooth.device.action.ACL_CONNECTED");
intentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED");
intentFilter.addAction("android.bluetooth.device.action.BOND_STATE_CHANGED");
intentFilter.addAction("android.bluetooth.device.action.NAME_CHANGED");
intentFilter.addAction("android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED");
intentFilter.addAction("android.bluetooth.adapter.action.STATE_CHANGED");
intentFilter.addAction("android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED");
intentFilter.addAction("android.bluetooth.headset.action.VENDOR_SPECIFIC_HEADSET_EVENT");
intentFilter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");
intentFilter.addAction("android.bluetooth.a2dp.profile.action.PLAYING_STATE_CHANGED");
intentFilter.addCategory("android.bluetooth.headset.intent.category.companyid.76");
return intentFilter;
}
@Override
public void onReceive (Context context, Intent intent) {
BluetoothDevice bluetoothDevice = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
// Bluetooth turned off, stop scanner and remove notification.
if (state == BluetoothAdapter.STATE_OFF || state == BluetoothAdapter.STATE_TURNING_OFF)
onStop();
// Bluetooth turned on, start/restart scanner.
if (state == BluetoothAdapter.STATE_ON)
onStart();
}
// Airpods filter
if (bluetoothDevice != null && action != null && !action.isEmpty()) {
// Airpods connected, show notification.
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
onConnect(bluetoothDevice);
// Airpods disconnected, remove notification but leave the scanner going.
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action) || BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action))
onDisconnect(bluetoothDevice);
}
}
}
@@ -0,0 +1,31 @@
package com.dosse.airpods.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public abstract class ScreenReceiver extends BroadcastReceiver {
public abstract void onStart ();
public abstract void onStop ();
public static IntentFilter buildFilter () {
IntentFilter screenIntentFilter = new IntentFilter();
screenIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
screenIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
return screenIntentFilter;
}
@Override
public void onReceive (Context context, Intent intent) {
switch (intent.getAction()) {
case Intent.ACTION_SCREEN_OFF: onStop();
break;
case Intent.ACTION_SCREEN_ON: onStart();
break;
}
}
}
@@ -1,10 +1,12 @@
package com.dosse.airpods;
package com.dosse.airpods.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import com.dosse.airpods.pods.PodsService;
import java.util.Objects;
/**
@@ -1,4 +1,4 @@
package com.dosse.airpods;
package com.dosse.airpods.ui;
import android.content.Intent;
import android.net.Uri;
@@ -8,6 +8,8 @@ import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.dosse.airpods.R;
public class AboutActivity extends AppCompatActivity {
@@ -1,4 +1,4 @@
package com.dosse.airpods;
package com.dosse.airpods.ui;
import android.Manifest;
import android.annotation.SuppressLint;
@@ -16,6 +16,7 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.dosse.airpods.R;
import com.dosse.airpods.utils.PermissionUtils;
import java.util.Locale;
@@ -1,4 +1,4 @@
package com.dosse.airpods;
package com.dosse.airpods.ui;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
@@ -14,6 +14,8 @@ import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.dosse.airpods.R;
import com.dosse.airpods.receivers.Starter;
import com.dosse.airpods.utils.PermissionUtils;
import java.util.Objects;
@@ -1,9 +1,11 @@
package com.dosse.airpods;
package com.dosse.airpods.ui;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.dosse.airpods.R;
public class NoBTActivity extends AppCompatActivity {
@Override
@@ -1,4 +1,4 @@
package com.dosse.airpods;
package com.dosse.airpods.ui;
import android.content.SharedPreferences;
import android.os.Bundle;
@@ -8,6 +8,9 @@ import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;
import com.dosse.airpods.R;
import com.dosse.airpods.receivers.Starter;
import java.util.Objects;
public class SettingsActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
@@ -1,4 +1,4 @@
package com.dosse.airpods;
package com.dosse.airpods.ui;
import android.content.ComponentName;
import android.content.Context;
@@ -12,10 +12,13 @@ import androidx.appcompat.app.AlertDialog;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import static com.dosse.airpods.AboutActivity.donateURL;
import static com.dosse.airpods.AboutActivity.fdroidURL;
import static com.dosse.airpods.AboutActivity.githubURL;
import static com.dosse.airpods.AboutActivity.websiteURL;
import static com.dosse.airpods.ui.AboutActivity.donateURL;
import static com.dosse.airpods.ui.AboutActivity.fdroidURL;
import static com.dosse.airpods.ui.AboutActivity.githubURL;
import static com.dosse.airpods.ui.AboutActivity.websiteURL;
import com.dosse.airpods.BuildConfig;
import com.dosse.airpods.R;
public class SettingsFragment extends PreferenceFragmentCompat {
@@ -0,0 +1,21 @@
package com.dosse.airpods.utils;
import android.util.Log;
import com.dosse.airpods.BuildConfig;
public class Logger {
// Log is only displayed if this is a debug build, not release
private static final boolean ENABLE_LOGGING = BuildConfig.DEBUG;
public static final String TAG = "AirPods";
public static void debug (String msg) {
if (ENABLE_LOGGING) Log.d(TAG, msg);
}
public static void error (Throwable t) {
if (ENABLE_LOGGING) Log.e(TAG, "ERROR", t);
}
}
@@ -1,23 +0,0 @@
package com.dosse.airpods.utils;
import static com.dosse.airpods.utils.ScannerUtils.isMax;
import android.view.View;
import com.dosse.airpods.R;
public class NotificationUtils {
public static String statusToString (int status) {
return (status == 10) ? "100%" : ((status < 10) ? ((status * 10 + 5) + "%") : "");
}
public static int batImgSrcId (boolean charge) {
return charge ? R.drawable.ic_battery_charging_full_green_24dp : R.drawable.ic_battery_alert_red_24dp;
}
public static int batImgVisibility (boolean charge, int status) {
return ((charge && status <= 10 && !isMax()) || status <= 1) ? View.VISIBLE : View.GONE;
}
}
@@ -1,30 +0,0 @@
package com.dosse.airpods.utils;
import com.dosse.airpods.PodsService;
public class ScannerUtils {
/*
* Decodes the byte array to a hexadecimal string
*/
public static String decodeHex (byte[] bArr) {
StringBuilder ret = new StringBuilder();
for (byte b : bArr)
ret.append(String.format("%02X", b));
return ret.toString();
}
public static boolean isFlipped (String str) {
return (Integer.parseInt("" + str.charAt(10), 16) & 0x02) == 0;
}
/*
* Check if model is airpods max
*/
public static boolean isMax () {
return PodsService.model.equals(PodsService.MODEL_AIRPODS_MAX);
}
}
@@ -7,7 +7,7 @@
android:paddingLeft="@dimen/padding_default"
android:paddingTop="@dimen/padding_default"
android:paddingRight="@dimen/padding_default"
tools:context=".AboutActivity"
tools:context=".ui.AboutActivity"
tools:ignore="ContentDescription,ButtonStyle">
<ImageView
@@ -7,7 +7,7 @@
android:paddingLeft="@dimen/padding_default"
android:paddingTop="@dimen/padding_default"
android:paddingRight="@dimen/padding_default"
tools:context=".AboutActivity"
tools:context=".ui.AboutActivity"
tools:ignore="ContentDescription,ButtonStyle">
<ImageView
@@ -4,4 +4,4 @@
android:id="@+id/settings_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SettingsActivity" />
tools:context=".ui.SettingsActivity" />