4

I have a class that extends AccessibilityService and when there is a certain event starts an activity.

The problem is that when the activity ends, it should send data back to 'AccessibilityService'. Does anyone have an idea on how to do that?

Example:

public class MyAccessibilityService extends AccessibilityService {

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

        if (event.getEventType()==AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED){
                Intent intent=new Intent(getApplicationContext(),DialogActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                startActivity(intent);
                // String resul=set result When Activity is closed
        }
    }

Thanks in advance!

Hejazi
  • 16,587
  • 9
  • 52
  • 67

2 Answers2

7

AccesibilityService is an inherited class from Service class. So we can refer that question to this: How to have Android Service communicate with Activity

The easiest way for your question:

1) Call startService() in your Activity's onDestroy() method:

@Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(getApplicationContext(), MyAccessibilityService.class);
        intent.putExtra("data","yourData");
        startService(intent);
    }

2) Override your MyAccessibilityService's onStartCommand() method:

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        String data="";
        if(intent.getExtras().containsKey("data"))
            data = intent.getStringExtra("data");
        return START_STICKY;
    }
Community
  • 1
  • 1
Sait Banazili
  • 1,263
  • 2
  • 12
  • 27
  • This is the easiest way to do this. Make sure that the data you're sending is paracable. The other option is via Binders – miversen33 Jan 03 '17 at 00:56
  • 1
    As described in this post https://stackoverflow.com/questions/9313472/how-to-start-accessibilityservice/12336085 the service gets automatically started. So, how we can pass data to Accessibility service @negative_zero ? – Raj Dec 13 '19 at 19:35
-2

1)Call startActivity(intent) from your accessibility service on any event.

    String msg = "your message";
    Intent intent = new Intent(serviceContext, activityClassName.class);
    intent.putExtra("message",msg);
    startActivity(intent);

2)Now in your activities onCreate(Bundle bundle) method you can get intent.

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        String msg = intent.getStringExtra("message");
        Log.e(LOG_TAG,"Message From Service - "+msg); //Message From Service - your message
    }

Using Intent you can pass data from Service to Activity.

Ashfaq
  • 137
  • 5