Android - WallpaperService why does my Engine have to be a inner class?
Asked Answered
D

2

6

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?

Disinclination answered 16/8, 2010 at 14:55 Comment(0)
P
4

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."

Porosity answered 16/8, 2010 at 15:20 Comment(1)
Actually it says you CANNOT do it that way, essentially if you can't use WallpaperService.this to refer to the parent WallpaperService instance then it's not going to function within the live wallpaper framework's restrictions.Brezin
C
0

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.

Chaschase answered 3/4, 2013 at 0:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.