【发布时间】:2018-04-08 20:23:47
【问题描述】:
我想实现一个功能,在单击按钮时,我们会在长按电源按钮时看到 android 的菜单,然后用户可以选择关闭设备。
我说的是这个菜单
我需要它没有根。商店里有一个应用程序,无需root即可完成。 https://play.google.com/store/apps/details?id=com.jjo.lockScreenButton
【问题讨论】:
我想实现一个功能,在单击按钮时,我们会在长按电源按钮时看到 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 访问权限并使用these options for shutting down or rebooting 设备。
如果您的应用程序是标准消费者应用程序,我建议让他们使用设备的标准接口关闭设备。
【讨论】: