Android - WallpaperService, why should my engine be an inner class?

I am working on simple android live wallpapers, I am following chapter 12 of Hello, Android as my guide.

The bare bones of the wallpaper look like this:

public class MyWallpaper extends WallpaperService { private class MyEngine extends Engine { //... } //... } 

According to the book MyEngine must will be the inner class MyWallpaper . I have no reason to argue about this, but the book does not explain why this is so. I prefer not to use inner classes solely for stylistic / aesthetic reasons.

I was wondering if MyEngine should really be a private inner class, and if so, why?

+4
source share
2 answers

You have to do it like this because the class Engine nested in the abstract class WallpaperService . If you try to make this non-nested, your IDE / compiler will tell you the following:

No instance of an instance of type WallpaperService is available to call the super constructor. Must define the constructor and explicitly qualify its super-constructor call with an instance of WallpaperService (for example, x.super (), where x is an instance of WallpaperService).

Which, freely translated, means "you could do it this way, but it would look uglier than if you only used a nested class."

+4
source

You can use your engine in a separate class. I just tried it with my own wallpaper, and it compiled and works fine.

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

EDIT: Thinking about what Justin Booster said, I'm not sure my advice is good. Your engine will lose access to WallpaperService members because they will all have to go through wallpaperSvcObject. I do not know what he had in mind.

0
source

All Articles