I am using the IntentService to change wallpaper in the background. It gets invoked on receiving of a push notification. Below code works fine if notification is received while the application is open. But does not work if the Application is closed/killed (by swiping it away with help of menu button)
@Override
protected void onHandleIntent(Intent intent) {
//Toast.makeText(this, "Intent", Toast.LENGTH_SHORT).show();
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String imageUrl = intent.getExtras().getString("imageUrl");
try {
URL url;
try {
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(MySingletonClass.mainActivityInstance);
url = new URL(
imageUrl);
Bitmap bmp = BitmapFactory.decodeStream(url
.openConnection().getInputStream());
myWallpaperManager.setBitmap(bmp);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
PushReceiver.completeWakefulIntent(intent);
}
Works fine when the application is opened. When closed/killed, it isn't able to create instance of WallpaperManager and throws below exception.
W/System.err: java.lang.NullPointerException
W/System.err: at android.app.WallpaperManager.getInstance(WallpaperManager.java:361)
Instead of using MySingletonClass.mainActivityInstance
which was actually null as pointed by @qbix, Use context of the IntentService which is this
.
try {
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(this);
url = new URL(
imageUrl);
Bitmap bmp = BitmapFactory.decodeStream(url
.openConnection().getInputStream());
myWallpaperManager.setBitmap(bmp);
}