3

We can get Touch events for each Activity by using getWindow() on context like :

//set Window.Callback for getting touch event 
        final Window window = context.getWindow();
        final Window.Callback localCallback = window.getCallback();
        window.setCallback(new MyWindowCallback(localCallback));

How can we achieve it without using context ?

Is there any way to remove this callback (Because window class don't have any remove callback methods ?

Vivek Pratap Singh
  • 1,564
  • 16
  • 26
N Kaushik
  • 2,198
  • 18
  • 29
  • 1
    "How can we achieved it without using context ?" - You can't, really. You could instantiate your own Window, but you'd still need a Context to do that. What are you trying to do? – Mike M. Dec 04 '15 at 05:54
  • how about `win.setCallback(null)` ? to remove the listener? – Kosh Dec 04 '15 at 05:55
  • Applicallication crashes if you set to null. @MikeM. I think we can do : check these comments : http://stackoverflow.com/questions/25441531/detect-every-touch-events-without-overriding-dispatchtouchevent/25842377?noredirect=1#comment55915947_25842377 – N Kaushik Dec 04 '15 at 05:59
  • why would you want to remove callback? – Adhikari Bishwash Dec 04 '15 at 06:04
  • Yes, but you still need a Context. If you mean you need to get a Context outside of a class that has access to one, you should explain that more clearly in your question. – Mike M. Dec 04 '15 at 06:06

1 Answers1

5

There's a way to get Application context without passing it. I have used this code in production environment and this works fine.

private static Application getApplicationContext() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    Context context;
    final Class<?> activityThreadClass =
            Class.forName("android.app.ActivityThread");
    final Method method = activityThreadClass.getMethod("currentApplication");
    context = (Application) method.invoke(null, (Object[]) null);
    Log.d(tag_, "Context is " + context);
    application = (Application)context;
    return application;
}
Adhikari Bishwash
  • 2,770
  • 28
  • 32