单击按钮如何在android上显示电源关闭菜单?

She*_*az 3 android android-intent

我要实现一项功能,在该功能上,单击按钮会出现android菜单,我们可以在长按电源按钮的情况下看到该菜单,然后用户可以选择关闭设备。

我说的是这个菜单

在此处输入图片说明

我需要它没有根。商店中有一个无需root即可执行的应用程序。 https://play.google.com/store/apps/details?id=com.jjo.lockScreenButton

小智 5

我可能迟到了,但是有可能。为此,您必须使用可访问性服务,用户必须允许其访问。另外,请记住,可访问性服务旨在帮助残障人士,而不是针对此用例。

1.创建一个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);
}
}
Run Code Online (Sandbox Code Playgroud)

确保com.yourapp用您的应用程序包替换

2.在清单中注册服务

<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>
Run Code Online (Sandbox Code Playgroud)

3. accessibility_service.xml

在您的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" />
Run Code Online (Sandbox Code Playgroud)

再次,替换com.yourapp。您还应该提供说明。此处提供更多信息:https : //developer.android.com/guide/topics/ui/accessibility/services.html#service-config

4.显示菜单

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);
Run Code Online (Sandbox Code Playgroud)

摘自:https : //github.com/farmerbb/Taskbar


Tan*_*.7x 0

你不可以做这个。

对话框本身是系统的一部分,不会以任何方式暴露给应用程序开发人员。

您可以自己模仿该对话框,但该框架也没有公开让您以编程方式启动关闭或重新启动的方法。

如果您确实想走这条路线,您还可能需要应用程序的 root 访问权限,并使用这些选项来关闭或重新启动设备。

如果您的应用程序是标准消费者应用程序,我建议让他们使用设备的标准接口来关闭设备。