Friday, 12 April 2013

Simple Image Viewer And Wallpaper Setter - Android

In this tutorial, we will see how to create an Image Viewer and to set Wallpaper for Android

Objectives:

1) Design the UI with one ImageView component and two Button Components
2) Button Next shows the next image and other button Set Wallpaper sets the current image as wallpaper
3) Errors are shown using Toast.makeToast() method

Steps:

1) Desgin the screen as follows:

2) Set the permission for using Wallpaper in AndroidManifest.xml file

<uses-permission android:name="android.permission.SET_WALLPAPER" >
</uses-permission>
3) Place the Image files under res\drawable-xhdpi folder

4) Implement the Next Button operation
int counter = 1;String currentImage = "";
public void showNextImage(View view) {
try {
ImageView iv = (ImageView) findViewById(R.id.
imageView1);
currentImage = "drawable/i" + counter;
iv.setImageDrawable(getResources().getDrawable(
getResources().getIdentifier(
currentImage, "drawable",
getPackageName())));
counter++;
if (counter > 6)
counter = 1;
}
catch (Exception e) {
Toast.makeText(
this, "Error Loading Image", Toast.LENGTH_SHORT)
.show();
}
}
5) Implement the set Wallpaper method

Handler
handler=new Handler();
public void setCurrentImageAsWallpaper(View view) {
Thread th =
new Thread() {
public void run() {
WallpaperManager wallpaperManager = WallpaperManager
.getInstance(MainActivity.
this);
try {
wallpaperManager.setResource(
getResources().getIdentifier(
currentImage, "drawable",
getPackageName()));
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.
this, "Wallpaper set",
Toast.
LENGTH_SHORT).show();
}
});
}
catch (Exception e) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.
this,
"Error setting wallpaper",
Toast.
LENGTH_SHORT).show();
}
});
}
}
};
th.start();
}



Result:


No comments:

Post a Comment