如何将数据从Activity发送回AccessibilityService?

时间:2016-11-26 12:18:45

标签: android android-intent accessibilityservice

我有一个扩展AccessibilityService的类,当有某个事件开始活动时。

问题是,当活动结束时,它应该将数据发送回' AccessibilityService'。有没有人知道如何做到这一点?

示例:

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
        }
    }

提前致谢!

2 个答案:

答案 0 :(得分:5)

AccesibilityService是Service类的继承类。所以我们可以将这个问题提到这个: {{3}}

您问题的最简单方法:

1)在Activity的onDestroy()方法中调用startService():

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

2)覆盖MyAccessibilityService的onStartCommand()方法:

 @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;
    }

答案 1 :(得分:-1)

1)在任何事件中从您的辅助功能服务中调用startActivity(intent)。

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

2)现在,在您的活动onCreate(Bundle bundle)方法中,您可以获得意图。

    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
    }

使用Intent,您可以将数据从Service传递到Activity。