如何onUnbind AccessibilityService

时间:2017-05-22 15:40:09

标签: accessibilityservice

我创建了一个ActivityMonitorService,它扩展了AccessibilityService以捕获TYPE_WINDOW_STATE_CHANGED事件。但是当我强行关闭我的应用程序时,手机会一直重启。 onUnbind()是在主要活动onDestroy()时调用的,但每次手机重启后,ActivityMonitorService都会重启并因某些原因重启我的手机。请给我一些建议。

ActivityMonitorService.java

public class ActivityMonitorService extends AccessibilityService {
public static final String LOG_TAG = "ActivityMonitorService";
private MyBinder myBinder = new MyBinder();

public class MyBinder extends Binder {
    public ActivityMonitorService getService()
    {
        return ActivityMonitorService.this;
    }
}

@Override
public void onRebind(Intent intent) {
    super.onRebind(intent);
    Log.i(LOG_TAG, "--------onRebind--------");
}

@Override
public boolean onUnbind(Intent intent) {
    Log.i(LOG_TAG, "--------onUnbind--------");
    return super.onUnbind(intent);
}

@Override
public void onCreate() {
    super.onCreate();
    Log.i(LOG_TAG, "--------onCreate--------");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(LOG_TAG, "--------onStartCommand--------");

    int i = super.onStartCommand(intent, flags, startId);
    Log.e(LOG_TAG,"--------onStartCommand--------, i = " + i +",START_NOT_STICKY="+ START_NOT_STICKY);

    return START_NOT_STICKY;
}


@Override
protected void onServiceConnected() {
    Log.i(LOG_TAG,"onServiceConnected enter");
    super.onServiceConnected();

    //Configure these here for compatibility with API 13 and below.
    AccessibilityServiceInfo config = new AccessibilityServiceInfo();
    config.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
    config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
    config.notificationTimeout = 100;
    if (Build.VERSION.SDK_INT >= 16)
        //Just in case this helps
        config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;

    setServiceInfo(config);
    Log.i(LOG_TAG,"onServiceConnected");
}

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    Log.i(LOG_TAG,"onAccessibilityEvent");
    if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
        ComponentName componentName = new ComponentName(
                event.getPackageName().toString(),
                event.getClassName().toString()
        );

        ActivityInfo activityInfo = tryGetActivity(componentName);
        boolean isActivity = activityInfo != null;
        if (isActivity)
            Log.i("CurrentActivity", componentName.flattenToShortString());
    }
}

private ActivityInfo tryGetActivity(ComponentName componentName) {
    try {
        return getPackageManager().getActivityInfo(componentName, 0);
    } catch (PackageManager.NameNotFoundException e) {
        return null;
    }
}

@Override
public void onInterrupt() {}

@Override
public void onDestroy() {
    Log.i(LOG_TAG, "--------onDestroy--------");
    super.onDestroy();
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "MainActivity";
public static int OVERLAY_PERMISSION_REQ_CODE = 1234;

private boolean isBoundMonitorService = false;
private ActivityMonitorService monitorService = null;//get minitor service through binder
private ActivityMonitorService.MyBinder myBinder = null;
private ServiceConnection monitorConnection = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.e(ActivityMonitorService.LOG_TAG, "------onServiceDisconnected---------");
        isBoundMonitorService = false;
    };

    public void onServiceConnected(ComponentName name, IBinder service) {
        isBoundMonitorService = true;
        Log.e(ActivityMonitorService.LOG_TAG, "------onServiceConnected---------");
        //myBinder = (ActivityMonitorService.MyBinder)service;
        //monitorService = myBinder.getService();
    };
};


    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!Settings.canDrawOverlays(this)) {
            Toast.makeText(MainActivity.this, "no permission", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
        }
    }
    Log.d(LOG_TAG, "onCreate");
    //WindowUtils.showPopupWindow(getApplicationContext());
    Intent ServiceIntent = new Intent(this, ServiceUtils.class);
    startService(ServiceIntent);

    Intent AndroidMonitorServiceIntent = new Intent(this, ActivityMonitorService.class);
    bindService(AndroidMonitorServiceIntent,monitorConnection,BIND_AUTO_CREATE);//
    Log.e(ActivityMonitorService.LOG_TAG, "------bindService---------");

    //finish();
}

@Override
protected  void onDestroy(){
    if(isBoundMonitorService)
    {
        Log.e(ActivityMonitorService.LOG_TAG, "------unbindService---------");
        unbindService(monitorConnection);
        isBoundMonitorService = false;
    }

    super.onDestroy();
    //Intent ServiceIntent = new Intent(this, ServiceUtils.class);
    //stopService(ServiceIntent);
    //finish();
}

}

的AndroidManifest.xml

 <service
        android:name=".util.ActivityMonitorService"
        android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
        android:enabled = "true"
        android:exported = "false">
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService"/>
        </intent-filter>
        <meta-data
            android:name="android.accessibilityservice"
            android:resource="@xml/accessibilityservice"/>
    </service>

XML / accessibilityservice.xml

<accessibility-service
xmlns:tools="http://schemas.android.com/tools"
android:accessibilityEventTypes="typeWindowStateChanged"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagIncludeNotImportantViews"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:ignore="UnusedAttribute"/>

添加一些日志


    05-24 08:32:44.989 8313-8313/? I/HwLauncher: Launcher  Launcher.onStart() cost 1 ms
05-24 08:32:44.989 6778-6814/? W/WindowManager: Attempted to remove non-existing token: android.os.Binder@342478f
05-24 08:32:44.989 8313-8313/? I/HwLauncher: Launcher onResume()
05-24 08:32:44.989 8313-8430/? E/HwLauncher: SettingsEx , no such field.
05-24 08:32:44.989 8313-8313/? I/HwLauncher: Launcher doResumeWork()
05-24 08:32:44.989 8313-8430/? W/HwLauncher: Clock getDataFormat the getSystemString failed.
05-24 08:32:44.990 6778-6814/? E/AndroidRuntime: *** FATAL EXCEPTION IN SYSTEM PROCESS: android.bg
                                                 java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.PACKAGE_RESTARTED dat=package:com.example.org.floatwindow flg=0x10 (has extras) } in com.android.server.accessibility.AccessibilityManagerService$1@5de13ec
                                                     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1235)
                                                     at android.os.Handler.handleCallback(Handler.java:761)
                                                     at android.os.Handler.dispatchMessage(Handler.java:98)
                                                     at android.os.Looper.loop(Looper.java:156)
                                                     at android.os.HandlerThread.run(HandlerThread.java:61)
                                                  Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.os.IBinder.unlinkToDeath(android.os.IBinder$DeathRecipient, int)' on a null object reference
                                                     at com.android.server.accessibility.AccessibilityManagerService$Service.unlinkToOwnDeathLocked(AccessibilityManagerService.java:3122)
                                                     at com.android.server.accessibility.AccessibilityManagerService$Service.onRemoved(AccessibilityManagerService.java:3113)
                                                     at com.android.server.accessibility.AccessibilityManagerService.removeServiceLocked(AccessibilityManagerService.java:1145)
                                                     at com.android.server.accessibility.AccessibilityManagerService.-wrap22(AccessibilityManagerService.java)
                                                     at com.android.server.accessibility.AccessibilityManagerService$Service.unbindLocked(AccessibilityManagerService.java:2385)
                                                     at com.android.server.accessibility.AccessibilityManagerService.updateServicesLocked(AccessibilityManagerService.java:1307)
                                                     at com.android.server.accessibility.AccessibilityManagerService.onUserStateChangedLocked(AccessibilityManagerService.java:1445)
                                                     at com.android.server.accessibility.AccessibilityManagerService.-wrap19(AccessibilityManagerService.java)
                                                     at com.android.server.accessibility.AccessibilityManagerService$1.onHandleForceStop(AccessibilityManagerService.java:343)
                                                     at com.android.internal.content.PackageMonitor.onReceive(PackageMonitor.java:388)
                                                     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1222)
                                                     at android.os.Handler.handleCallback(Handler.java:761)?
                                                     at android.os.Handler.dispatchMessage(Handler.java:98)?
                                                     at android.os.Looper.loop(Looper.java:156)?
                                                     at android.os.HandlerThread.run(HandlerThread.java:61)?

1 个答案:

答案 0 :(得分:0)

您无法从活动中启动AccessibilityServices。辅助功能服务从

开始
  

设置&gt;辅助功能

手机上的区域。您无法以尝试的方式启动辅助功能服务。