I want to be able to restart my WatchFaceSerivce in so that I can trigger the onCreateEngine() method again and set an alternate wallpaper.
However, the Android service I am trying to restart is putting up a real fight, it almost seems as though the code has no effect although I have made sure it is getting called.
stopService(new Intent(getApplicationContext(), MyWatchfaceService.class));
startService(new Intent(getApplicationContext(), MyWatchfaceService.class));
Is there a way I can force restart my service in Android to trigger the onCreateEngine or set the Engine to an alternate watch face after the first time the service starts?
Wallpapers are governed by the WallpaperManager
, which mostly has methods that are available to system apps only. It's the WallpaperManager
that will start and stop your service.
My suggestion to you is to change your architecture a little bit. You need only one WatchFaceService
subclass and only Engine
subclass and you never need to restart any of them. Instead, inside of Engine
you should have multiple watch face drawers. So your structure is like this:
WatchFaceService
Engine
AnalogWatchFaceDrawer
DigitalWatchFaceDrawer
FancyWatchFaceDrawer
FitnessWatchFaceDrawer
WeatherWatchFaceDrawer
No, if you want to change which watch face is drawn, you should just change current drawer and force an immediate redraw.
EDIT: For drawing, all you will do is pass the canvas and bounds to the current drawer and let it do the work, so your code will look like this:
@Override
public void onDraw(Canvas canvas, Rect bounds) {
if (mCurrentWatchFaceDrawer != null) {
mCurrentWatchFaceDrawer.draw(canvas, bounds);
}
}
So you defer all the drawing logic to each drawer and let them do the work independently.
As for loading some resources, your drawers will have to have some lifecycle. So, they need their own callbacks like onCreate
and onDestroy
. When you set a new drawer, you call its onCreate
and it will the images and when it goes away, you call onDestroy
, so it can clean up after itself. So, your drawer right now should have interface like this:
public interface WatchFaceDrawer {
void onCreate();
void onDestroy();
void draw(Canvas canvas, Rect bounds);
}
You will probably need to add more to handle other events.