Xamarin.Android:如何永久打开辅助功能服务

时间:2017-04-18 19:45:39

标签: android xamarin

我编写了辅助功能服务,以防止在USSD请求期间打开AlertWindow:

    [Service(Label = "BalanceAccessibilityService", Permission = "android.permission.BIND_ACCESSIBILITY_SERVICE")]
[IntentFilter(new string[] { "android.accessibilityservice.AccessibilityService" })]
public class BalanceAccessibilityService : AccessibilityService
{
    static readonly string Tag = "SmsService:" + typeof(BalanceAccessibilityService).Name;
    protected override void OnServiceConnected()
    {
        base.OnServiceConnected();
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.Flags = AccessibilityServiceFlags.Default;
        info.PackageNames = new string[] { "com.android.phone" };
        info.EventTypes = EventTypes.WindowStateChanged;
        info.FeedbackType = FeedbackFlags.Generic;
        SetServiceInfo(info);
    }

    public override void OnAccessibilityEvent(AccessibilityEvent e)
    {
        Log.Info(Tag, $"onAccessibilityEvent: type = {e.EventType.ToString()} package = {e.PackageName}");

        AccessibilityNodeInfo info = e.Source;

        if (e.EventType == EventTypes.WindowStateChanged && !e.PackageName.Equals("com.android.phone"))
            return;
        if (e.EventType == EventTypes.WindowContentChanged && (info == null || !info.ClassName.Equals("android.widget.TextView")))
            return;
        if (e.EventType == EventTypes.WindowContentChanged && TextUtils.IsEmpty(info.Text))
            return;
        if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            PerformGlobalAction(GlobalAction.Back);
        else
        {
            Intent intent = new Intent(Intent.ActionCloseSystemDialogs);
            SendBroadcast(intent);
        }
    }

    public override void OnInterrupt()
    {
        Log.Info(Tag, "OnInterrupt");
    }
}

一切正常,但问题是,当我的应用程序在设置 - >辅助功能 - >服务 - > BalanceAccessibilityService关闭时停止了切换。因此,如果我再次启动我的应用程序而不再用手切换此切换器,我的服务无法启动。现在我在MainActivity的onCreate方法中使用这样的代码进行交换:

        Intent intent = new Intent(Settings.ActionAccessibilitySettings);
        StartActivityForResult(intent, 0);

但我认为这是不正常的,因为对于其他服务,例如Power Clean或Android Assistance,它应该一次性切换它们并且它们永远不会自行关闭。 任何人都可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:0)

我使用Xamarin Studio启动我的应用程序。在那种情况下停止应用程序服务关闭后。如果我手动启动应用程序,则不会关闭