I have an Android widget (extends the AppWidgetProvider
class) and I'm trying to access the application context from within a service Listener. I need to access the context so that I can change the application wallpaper. Here's the error I get: Cannot refer to a non-final variable context inside an inner class defined in a different method
. I tried the suggested fix to change the modifier context to Final but the Bitmap I create comes back as null. Can someone suggestion the appropriate way to handle this? Here's a snippet of the code:
private void startWallpaperService(Context context) {
Intent wpIntent = new Intent(context, Wallpaper_Service.class);
context.startService(wpIntent);
Wallpaper_Service wpSrv = Wallpaper_Service.getService();
if(wpSrv != null) {
Log.i(TAG, "Wallpaper Service is not null");
Wallpaper_Service.repetitionInterval=30*1000;
wpSrv.setWallpaperListener(new Wallpaper_Service.WallpaperListener() {
@Override
public void onWallpaperUpdate(int imageId) {
if(wpm == null)
Log.w(TAG, "wpm or context is null");
else {
Bitmap background = BitmapFactory.decodeResource(context.getResources(), R.drawable.image1); // I get a syntax error here
if(background==null){
Log.w(TAG, "background is null");
}else{
try {
wpm.setBitmap(background);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
} else {
Log.e(TAG, "Wallpaper Service failed");
}
}
Can you just create a final application context instance in the third line of your method like:
final Context ctx = context.getApplicationContext();
or
final Context ctx = context;
And I presume you can now use the "ctx" in your inner method deceleration.
This just sounds like a java syntax limitation and not a code issue.
Hope this helps.
-serkan