Question: I am trying to archive same thing as done in "hierarchyviewer" tool, which dumps the tree of Views present at any given moment on the device or emulator screen. 

But i want it to be an Application running on a Android device. This app will keep running in background like a Serve and will dump the currently displayed Views in a text file. 

Is it possible? is there any code examples are available?

Answer: 
> 
> Is it possible?
> 
> 
> 

No.

The closest you can come is to implement an `AccessibilityService`. This would more closely mirror the **`uiautomatorviewer`** functionality, giving you a subset of what you see in Hierarchy View. This also requires a double-opt-in by the user: the user must install your app *and* activate it in Settings in the accessibility area.
As far as I know, you couldn't access other apps if they do not explicity share that info with you by the use of Intents (or if you own these other apps).

So, based on this limitation, my bets are you can't access another app's View Tree by regular means. And if you chould, I think you shouldn't, as this is somehow "secret" to other apps, and you'd be registering information without permission. In fact, what `hierarchyview` uses is, for sure, some sort of trick that directly uses internal private libraries of Android. Like taking a screenshot, that you can't do with the "default" implementation, but using these kind of testing tools.

That being said, check [this answer](https://stackoverflow.com/a/8132179/616225), where it shows how to get the current app in foreground. From here, getting the View tree should be impossible, but as long as you could call `getWindow()` on that app's current activity, [this could be done](http://developer.android.com/reference/android/app/Activity.html#getWindow()).