Get an instance of current activity?

What I'm trying to do is send a motion event to the current activity. I have a ComponentName of current activity from this code

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); // get the info from the currently running task List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); Log.d("current task :", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName()); ComponentName componentInfo = taskInfo.get(0).topActivity; 

Now that I have the name of the component, I want to send an event

 dispatchTouchEvent(MotionEvent ev) 

which is in the Activity class, and for this I need an instance of the current activity. I am stuck in a component name. How can I get an instance of an Activity so that I can send an event?

+6
source share
1 answer

Wow, thereโ€™s so much wrong with this issue, itโ€™s hard to figure out where to start! Let them be in order:

What I'm trying to do is send a motion event to the current activity.

Current foreground activity will receive motion events if it is not. The only way I can imagine that this makes sense is that your service has put the system window up, which is among all applications ... in which case I would strongly recommend that you not do this and just leave your activity plan processes the event.

I have a ComponentName of current activity from this code

ActivityManager.getRunningTasks () is not intended for normal application development. This is for tasks such as task management, etc. You should never write core programming logic that is dependent on the information returned by this function. This is begging, and in fact I can guarantee that such code breaks at some point. (What happens when multiple applications can run simultaneously in the front?)

I want to send an event

You really, really, should not copy motion events from one window and type them in another. The sending state will not be configured correctly, the state in the event will not be consistent (the event was configured using the source for the original window, and not for the new one into which you are stuffing it), etc. This is another great way to make a broken application that has a good chance of cracking in the future, if you can even clone it to make it work today.

I am stuck in a component name. How can I get an instance of an Activity so that I can send an event?

In fact, all you have is the name of the component. This has nothing to do with active instances. There is no magic way to turn this into an actual instance. It would be wrong to file it, because it can be easily ambiguous (if there were two instances of an instance of this instance).

I think you need to back up to the very beginning and see what you are actually trying to accomplish in order to get help in what a reasonable way to approach it. The path you have come to is pretty terminal at the moment.

+7
source

Source: https://habr.com/ru/post/914171/


All Articles