How to target a running app with a KeyEvent?
<p>my goal is to target with a keyevent a specific application running either in foreground or background from a background service.</p>

<p>I tried many solutions, but have not yet managed to do it.</p>

<p>The few solutions tried (all from a background running service): </p>

<hr>

<p>With a broadcast, I tried to target the first application (for example the phone app) that would manage the key event</p>

<pre><code>KeyEvent lKey1Up = new KeyEvent(KeyEvent.ACTION_UP,KeyEvent.KEYCODE_ENDCALL);
KeyEvent lKey1Dwn = new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_ENDCALL);
Intent lKey1UpIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
Intent lKey1DwnIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
lKey1UpIntent.putExtra(Intent.EXTRA_KEY_EVENT, lKey1Up);
lKey1DwnIntent.putExtra(Intent.EXTRA_KEY_EVENT, lKey1Dwn );
sendOrderedBroadcast(lKey1UpIntent, null);
sendOrderedBroadcast(lKey1DwnIntent, null);
</code></pre>

<p>=> Nothing happens with my foreground phone app when the broadcast is performed while I am in a phone call state (OFFHOOK). Indeed, I was nearly sure this would not work since I have no way to specificely target the phone app.</p>

<hr>

<p>With <strong><em>Instrumentation</em></strong>, I tried to target the application that has the focus :</p>

<pre><code>Instrumentation lInst  = new Instrumentation();
KeyEvent lKey1Up = new KeyEvent(KeyEvent.ACTION_UP,KeyEvent.KEYCODE_1);
KeyEvent lKey1Dwn = new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_1);
lInst.sendKeySync(lKey1Up);
lInst.sendKeySync(lKey1Dwn);
</code></pre>

<p>also tried with a single call to :</p>

<pre><code>lInst.sendKeyDownUpSync(KeyEvent.KEYCODE_1)
</code></pre>

<p>=> Application crashes (also during phone call)
looks like I cannot use Instrumentation out of a testing purpose </p>

<hr>

<p>Eventually, I thought about using </p>

<pre><code>superDispatchKeyEvent(KeyEvent)
</code></pre>

<p>but since I don't know how to target a specific window from the targeted running application (and I have none in my service, indeed), I don't know how to use it at all.</p>

<hr>

<p>And before anyone asks, I added the </p>

<blockquote>
  <p>android.permission.INJECT_EVENTS<br>
  android.permission.MODIY_PHONE_STATE</p>
</blockquote>

<p>in my manifest in order to be sure all I do is "allowed".</p>

<p>Then... thanks first for reading until here, and now :</p>

<ul>
<li>some of you know how I can manage to
do target a specific application with a
keystroke event from a service?</li>
<li>some of you know how to do the same with the phone application specificely?</li>
</ul>

<p>Thanks in advance for your help.</p>
