AccessibilityService stops receiving events on reboot

╄→尐↘猪︶ㄣ 提交于 2019-11-30 16:08:50

I was facing same problem. After a lot of attempt I found that this problem occurs with older version of android (eg.Jellybean). when device is powered off the service gets unbinded. But it is not rebinded on_Boot_Completed. As this problem doesn't appear on newer version of android I considered it as a android bug. Because only way to re-activate the service is turning off and restarting the service, I am using sharedPreference to keep track states of my service. when onUnbind onRebind or onServiceConnected is called I update my sharedPreference with the value I associated for it. Now, before using service I check that if the service called onRebind or onServiceConnected if not then I tell user to restart service or start working with my service.

If you are so confused then you can Include the bellow code in your accessibility service.

public static String AccessibilityPreference="AccessibilityPreference";
public static String isServiceBinded="isServiceBinded";
@Override
public void onServiceConnected() {
    Log.e(TAG, "ACC::onServiceConnected:************************* ");
    SharedPreferences p=getSharedPreferences(AccessibilityPreference,Context.MODE_PRIVATE);
    SharedPreferences.Editor e=p.edit();
    e.putBoolean(isServiceBinded,true);
    e.commit();
}
 @Override
public boolean onUnbind(Intent intent) {
    Log.e("onUnbind","onUnbind Called***************************************************");
    SharedPreferences p=getSharedPreferences(AccessibilityPreference,Context.MODE_PRIVATE);
    SharedPreferences.Editor e=p.edit();
    e.putBoolean(isServiceBinded,false);
    e.commit();
    return super.onUnbind(intent);
}

@Override
public void onRebind(Intent intent) {
    Log.e("onRebind","onRebind Called***************************************************");
    SharedPreferences p=getSharedPreferences(AccessibilityPreference,Context.MODE_PRIVATE);
    SharedPreferences.Editor e=p.edit();
    e.putBoolean(isServiceBinded,true);
    e.commit();
    super.onRebind(intent);
}
public static boolean isServiceBinded(SharedPreferences preferences){
   return preferences.getBoolean(isServiceBinded,true);
}

Then before start working with the service check if service is valid like bellow,

if(AccessibilityWorkService.isServiceBinded(getSharedPreferences(AccessibilityWorkService.AccessibilityPreference, Context.MODE_PRIVATE))){
//start working
}else {
//tell user to restart service
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!