我有一个Android小部件(扩展了AppWidgetProvider
类),我试图从服务侦听器中访问应用程序上下文。我需要访问上下文,以便我可以更改应用程序壁纸。这是我得到的错误:Cannot refer to a non-final variable context inside an inner class defined in a different method
。我尝试了建议的修复将修饰符上下文更改为Final,但我创建的位图返回为空。谁能建议一个合适的方法来处理这个问题?下面是一段代码:
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");
}
}
能否在方法的第三行创建一个最终的应用程序上下文实例,如:
final Context ctx = context.getApplicationContext();
或
final Context ctx = context;
我假设你现在可以在你的内部方法中使用"ctx"
这听起来像是java语法限制,而不是代码问题。
希望对你有帮助。
-serkan
在95%的情况下,总是在监听器中,你可以直接使用getApplicationContext()来获取上下文。
如果您需要获取系统资源的上下文,请使用
Resources.getSystem().getString(R.string.somestuffofmyown)
您可以在应用程序的任何地方使用它!