I might be late but this is possible. You have to use an accessibility service for that, which the user must allow access to. Also, keep in mind that accessibility services are meant to help handicapped people and not for this use case.
1. Create a PowerMenuService
public class PowerMenuService extends AccessibilityService {
private BroadcastReceiver powerMenuReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(!performGlobalAction(intent.getIntExtra("action", -1)))
Toast.makeText(context, "Not supported", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {}
@Override
public void onInterrupt() {}
@Override
public void onCreate() {
super.onCreate();
LocalBroadcastManager.getInstance(this).registerReceiver(powerMenuReceiver, new IntentFilter("com.yourapp.ACCESSIBILITY_ACTION"));
}
@Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(powerMenuReceiver);
}
}
make sure to replace com.yourapp
with your app package
2. Register service in Manifest
Add the following under the <application>
tag:
<service
android:name=".PowerMenuService"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data android:name="android.accessibilityservice"
android:resource="@xml/accessibility_service" />
</service>
3. accessibility_service.xml
In your xml resource directory create a file named accessibility_service.xml
which contains the following:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:packageNames="com.yourapp" />
Again, replace com.yourapp
. You should also provide a description. More info here: https://developer.android.com/guide/topics/ui/accessibility/services.html#service-config
4. Show menu
ComponentName component = new ComponentName(getApplicationContext(), PowerMenuService.class);
getApplicationContext().getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent = new Intent("com.yourapp.ACCESSIBILITY_ACTION");
intent.putExtra("action", AccessibilityService.GLOBAL_ACTION_POWER_DIALOG);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
Taken from: https://github.com/farmerbb/Taskbar