[英]How to show power off menu on android on the click of a button?
我要实现一项功能,在该功能上,单击按钮会出现android菜单,我们可以在长按电源按钮的情况下看到该菜单,然后用户可以选择关闭设备。
我说的是这个菜单
我需要它没有根。 商店中有一个无需root即可执行的应用程序。 https://play.google.com/store/apps/details?id=com.jjo.lockScreenButton
我可能迟到了,但是有可能。 为此,您必须使用可访问性服务,用户必须允许其访问。 另外,请记住,可访问性服务旨在帮助残障人士,而不是针对此用例。
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);
}
}
确保用您的应用程序包替换com.yourapp
在<application>
标记下添加以下内容:
<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>
在您的xml资源目录中,创建一个名为accessibility_service.xml
的文件,其中包含以下内容:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:packageNames="com.yourapp" />
再次,替换com.yourapp
。 您还应该提供说明。 此处提供更多信息: 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);
你不可以做这个。
对话框本身是系统的一部分,并且不会以任何方式向应用程序开发人员公开。
您可以自己模拟对话框,但是该框架也不会公开以编程方式启动关闭或重新启动的方法。
如果您确实想沿这条路线走,还可能需要对应用程序具有root访问权限,并使用这些选项关闭或重新启动设备。
如果您的应用程序是标准的消费类应用程序,我建议让他们使用其设备的标准接口关闭其设备。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.