title: Android - Adding a key listener to an activity programmatically
body: <p>All I want to do is programatically add an onKeyDown listener to an existing activity.  A little bit of context for what I want to do: I want to make a standalone function that handles click events that occur in a mediaplayer.  </p>
  
  <p>ie: Let's pretend I have this class.</p>
  
  <pre><code>public class Main extends Activity
  {    
  @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
              setContentView(R.layout.maingui);
      }
  
  @Override
       public boolean onKeyDown(int keyCode, KeyEvent event) {
           switch (keyCode) {
               case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
          }
          return false;
        }
  }
  </code></pre>
  
  <p>What I would like to do is add a function that adds the onKeyDown Listener through programming.</p>
  
  <p>ie: </p>
  
  <pre><code>    public class Main extends Activity
      {    
      @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
                  setContentView(R.layout.maingui);
  
                  createListener();
          }
  
  }
  public void createListener()
  {
      @Override
           public boolean onKeyDown(int keyCode, KeyEvent event) {
  
               switch (keyCode) {
                   case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
            }
              return false;
      }
  }
  </code></pre>
  
  <p>This obviously doesn't work, but gives you a good idea of what I'm trying to do.</p>
  
  <p>This is what I've tried which doesn't work. </p>
  
  <pre><code>    public class Main extends Activity
      {    
      @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
                  setContentView(R.layout.maingui);
  
              MyKeyClickClass.createListener(this);
      }
  
  }
  </code></pre>
  
  <ul>
  <li><p>Then Imagine this function in a MyKeyClickClass class </p>
  
  <pre><code>public static void createListener(Activity act)
      {      
          View testing = act.getWindow().getDecorView().findViewById(android.R.id.content);
  
          testing.setOnKeyListener(new OnKeyListener(){
  
              @Override
              public boolean onKey(View v, int keyCode, KeyEvent event) {
                  // TODO Auto-generated method stub
  
                  String test = "Hi";
  
                  return false;
              }
          });
      }
  </code></pre></li>
  </ul>
  
  <p>Is this possibly to do? I'm not getting any response to key events doing it this way. </p>
  
  <p>Cheers</p>