Question

I'm working on a simple android live wallpaper, I'm following chapter 12 from Hello, Android as my guide.

The bare-bones of a wallpaper service looks like this:

public class MyWallpaper extends WallpaperService {

    private class MyEngine extends Engine {
    //...
    }        

    //...

}

According to the book MyEngine must be an inner class of MyWallpaper. I have no reason to dispute this, but the book offers no explanation as to why this must be so. I prefer not to use inner classes purely for stylistic/aesthetic reasons.

I was wondering if MyEngine actually has to be a private inner class and, if so, why?

Was it helpful?

Solution

You're supposed to do it this way because class Engine is nested within the abstract class WallpaperService. If you try to make it not nested, your IDE/compiler will tell you something like this:

No enclosing instance of type WallpaperService is accessible to invoke the super constructor. Must define a constructor and explicitly qualify its super constructor invocation with an instance of WallpaperService (e.g. x.super() where x is an instance of WallpaperService).

Which, loosely translated, means "you could do it that way, but it's going to end up uglier than if you just use the nested class."

OTHER TIPS

You CAN have your Engine in a separate class. I just tried it with my own wallpaper and it compiled and runs fine.

In the onCreateEngine() override in your WallpaperService subclass, just pass 'this' to your Engine constructor. The constructor should receive it as a WallpaperService. In the first line of your constructor, make a call to wallpaperSvcObject.super().

EDIT: After thinking about what Justin Buser said, I'm not sure if my advice is good. Your Engine would lose access to members of WallpaperService because it'd all have to go through wallpaperSvcObject. I don't know if that's what he was referring to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top