'What's the best way to get the package name of the application in the foreground?

I'm working on an AOSP project and as part of that I'm modifying the Bluetooth SDK. I have made changes in android.bluetooth.BluetoothAdapter::getDefaultAdapter() method and I'd like to know which application has called that method.

There is a mContext member in that class and it's null in most of the cases and sometimes it's package name has values com.android.settings.This I guess is because applications calling BluetoothAdapter::getDefaultAdapter() doesn't have to pass the Context.

  1. So I'd like to know if there are any reliable means of getting the package name of the application that has called the getDefaultAdapter method?

  2. If that's not possible, then the next option is to get the package name of the application that's currently in the foreground. I tried printing the Pid and the Uid of android.os.Process and what I get is the process Id of the 'system' application. Are there any other methods which will help me get the package name of the application in the foreground?

  3. If that's also not possible then the only option left is to exec "dumpsys window windows | grep -E 'mObscuringWindow'" and parse the result. But I'm not quite sure whether this is advisable and reliable.

Any help will be greatly appreciated. Thanks!



Solution 1:[1]

You haven't mention Android Version Which you are using.

From Aosp Master branch perspective. Try with AttributionSource.myAttributionSource().getPackageName()

@Deprecated

@RequiresNoPermission
public static synchronized BluetoothAdapter getDefaultAdapter() {
    if (sAdapter == null) {
        sAdapter = createAdapter(AttributionSource.myAttributionSource());
    }
    return sAdapter;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashok Mutyala