I want to implement a functionality where on the click of a button the menu of android appear which we see on the long tap of power button, and then the user can choose to turn the device off.
I'm talking about this menu
I need it to be without root. There's an app on store which does it without requiring root. https://play.google.com/store/apps/details?id=com.jjo.lockScreenButton
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.
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
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>
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With