Tuesday, July 2, 2013

Android Live Wallpaper Tutorial

Live wallpapers   - are  richer, animated, interactive backgrounds on Homescreen.

In this post I will describe step by step "How to Create LiveWallpaper " .

  The Android Development Tutorials blog contains Basic as well as Advanced android tutorials.Go to Android Development Tutorials to get list of all Android Tutorials.

 

Android Live Wallpaper Example


In this example I have created a LiveWallpaper in which a Fish  is moving left to right.
The example is too simple and has been described in manner that you can easily  understand.

Android Live  Wallpaper


How to create a Live Wallpaper

Step 1: create a xml file which will describe your wallpaper.
Step 2: edit your manifest file add service and feature.
Step 3: create a service class which extends WallpaperService class.


Step 1:  create a xml folder inside res folder.
              inside xml folder create mywallpaper.xml file

             <?xml version="1.0" encoding="UTF-8"?>
            <wallpaper
                     xmlns:android="http://schemas.android.com/apk/res/android"
                     android:thumbnail="@drawable/fish"
                     android:description="@string/wallpaper_description" 
            />

here thumbnail is the image that will be shown in list of livewallpapers and description attribute is the description of your live wallpaper.

Also add following in your string.xml file inside values folder
<string name="wallpaper_description">Fish Aquarium</string>

Step 2: Edit your Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.livewallpapertutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

     <uses-feature
        android:name="android.software.live_wallpaper"
        android:required="true" >
    </uses-feature>


    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <service
            android:name="LiveWallpaperService"
            android:enabled="true"
            android:label="Wallpaper Example "
            android:permission="android.permission.BIND_WALLPAPER" >
            <intent-filter>
                <action android:name="android.service.wallpaper.WallpaperService" >
                </action>
            </intent-filter>

            <meta-data
                android:name="android.service.wallpaper"
                android:resource="@xml/mywallpaper" >
            </meta-data>

        </service>

    </application>

</manifest>



Step 3: create a service class which extends  WallpaperService.

this class is the base class for all live wallpapers in the system. You must implement the   onCreateEngine()   method .
The Engine class defines the life cycle methods, as for example onCreate(), onSurfaceCreated(), onVisibilityChanged(), onOffsetsChanged(), onTouchEvent() and onCommand()


public class LiveWallpaperService extends WallpaperService
{
                int x,y;
               
                public void onCreate()
                {
                        super.onCreate();
                }

                public void onDestroy()
                {
                        super.onDestroy();
                }

                public Engine onCreateEngine()
                {
                        return new MyWallpaperEngine();
                }

                class MyWallpaperEngine extends Engine
                {

                        private final Handler handler = new Handler();
                        private final Runnable drawRunner = new Runnable() {
                            @Override
                            public void run() {
                                draw();
                            }
                        };
                        private boolean visible = true;
                        public Bitmap image1,backgroundImage;

                        MyWallpaperEngine()
                        {
                                 // get the fish and background image references
                                image1 = BitmapFactory.decodeResource(getResources(),R.drawable.fish);
                                backgroundImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);
                                x=-130; // initialize x position
                                y=200;  // initialize y position
                               
                        }


                        public void onCreate(SurfaceHolder surfaceHolder)
                        {
                                super.onCreate(surfaceHolder);
                        }

                        @Override
                        public void onVisibilityChanged(boolean visible)
                        {
                                this.visible = visible;
                                // if screen wallpaper is visible then draw the image otherwise do not draw
                                if (visible)
                                {
                                    handler.post(drawRunner);
                                }
                                else
                                {
                                    handler.removeCallbacks(drawRunner);
                                }
                        }

                        @Override
                        public void onSurfaceDestroyed(SurfaceHolder holder)
                        {
                                super.onSurfaceDestroyed(holder);
                                this.visible = false;
                                handler.removeCallbacks(drawRunner);
                        }

                        public void onOffsetsChanged(float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels)
                        {
                                draw();
                        }

                        void draw()
                        {
                                final SurfaceHolder holder = getSurfaceHolder();
                 
                                Canvas c = null;
                                try
                                {
                                        c = holder.lockCanvas();
                                        // clear the canvas
                                        c.drawColor(Color.BLACK);
                                        if (c != null)
                                        {
                                                // draw the background image
                                                c.drawBitmap(backgroundImage, 0, 0, null);
                                                // draw the fish
                                                c.drawBitmap(image1, x,y, null);
                                                // get the width of canvas
                                                int width=c.getWidth();
                                               
                                                // if x crosses the width means  x has reached to right edge
                                                if(x>width+100)
                                                {  
                                                        // assign initial value to start with
                                                        x=-130;
                                                }
                                                // change the x position/value by 1 pixel
                                                x=x+1;
                                        }
                                 }
                                finally
                                {
                                        if (c != null)
                                               holder.unlockCanvasAndPost(c);
                                }

                                handler.removeCallbacks(drawRunner);
                                if (visible)
                                {
                                          handler.postDelayed(drawRunner, 10); // delay 10 mileseconds
                                }   

                        }
                }
}


Run the application and set the Wallpaper.( Long Press on Screen ->Set Wallpaper -> HomeScreen -> Live Wallpapers -> select your Live wall paper)

Android Live  Wallpaper




 

More Android Topics

New Advance Topics:
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swap Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation

 Beginning With Android
      Android : Introduction                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage
Working With Incoming Calls                                             DataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog





93 comments:

  1. nice and easy to understand

    ReplyDelete
  2. Thank you very much for your post.

    ReplyDelete
  3. Nice and easy, thanks a lot.

    ReplyDelete
  4. how to fit the background image in different screen sizes for different phones??? in live wallpaper apllication

    ReplyDelete
    Replies
    1. Image backImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);
      bitmap = Bitmap.createScaledBitmap(backImage, c.getWidth(), c.getHeight(), true);

      and draw this bitmap.
      It will fill the full screen.

      Delete
  5. how to fit the background images in different sizes ???

    ReplyDelete
    Replies
    1. Image backImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);
      bitmap = Bitmap.createScaledBitmap(backImage, c.getWidth(), c.getHeight(), true);

      where c is the object of canvas.
      and draw this bitmap.
      It will fill the full screen.

      Delete
  6. hi i did use your code i have an error
    image1 = BitmapFactory.decodeResource(getResources(),R.drawable.fish);
    backgroundImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);

    R. is creating errors how can i fix it

    ReplyDelete
    Replies
    1. Clean your project.
      Project->clean -> select your project.
      R.java will be recreated and you problem will be fixed.

      Delete
  7. This comment has been removed by a blog administrator.

    ReplyDelete
  8. Hi, I have an error on the Manifest on the line below:
    android:resource="@xml/mywallpaper" >
    It says "No resource found that matches the given name" any help please?

    ReplyDelete
    Replies
    1. Hi CoolGuru
      You have missed the first step.

      create a xml folder inside res folder.
      inside xml folder create mywallpaper.xml file


      Delete
  9. many exceptions detected

    ReplyDelete
    Replies
    1. This is a running example. But if you are getting Exception, Please tell me which Exceptions you are getting.

      Delete
  10. At point 3. Where you create class and what name have the class?

    ReplyDelete
    Replies
    1. At Point 3 I have created class LiveWallpaperService which extends WallpaperService.

      Delete
    2. In what directory should I create the LiveWallpaperService class? or should the code be added to another file? Would be grate if you had the fish and background pictures up for download and say where they should be placed.

      Delete
  11. but in which file? what's the name of the file?

    ReplyDelete
    Replies
    1. Can you please elaborate your problem that you are facing.

      Delete
  12. Hello
    I tried your tutorial and ia got 2 errors here:
    MyWallpaperEngine()
    {
    // get the fish and background image references
    image1 = BitmapFactory.decodeResource(getResources(),R.drawable.fish);
    backgroundImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);
    x=-130; // initialize x position
    y=200; // initialize y position

    }

    fish cannot be resolved or is not a field
    background cannot be resolved or is not a field

    I read your tutorial 3 times but i dont know what wemt wrong. Do you have any idea about this?

    ReplyDelete
    Replies
    1. Hi Richard
      You are facing this [problem because you do not have Required Images/Drawables.

      You must have 2 images with name "fish" and "background" in your drawable-mdpi folder inside res folder.

      Delete
  13. Nice tutorial. I've been searching for something like this for too long. Can we have the sample folder with the images?

    ReplyDelete
  14. Nice post! I've been trying understand something like that for too long. Is there any link to download the sample folder?

    ReplyDelete
  15. Hi,
    Good Example It works for me without errors.I have a question.I want change back grounds for every 30 sec .I have tried it,but i am unable to do.I have written background code in onvisibility method .
    backgroundImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);
    backgroundImage = BitmapFactory.decodeResource(getResources(),R.drawable.screen);
    here i have used 2 backgrounds.Here i'm seeing settings options when i click on it live wallpaper crashes what to do?

    ReplyDelete
  16. hi! very nice tutorial. but, after installing it in my device, it wont show in the apps list. What kind of activity/launcher should I make for this? thank you!

    ReplyDelete
  17. Awesome tutorial!. bt there is a problem occured to fit the background images in different sizes ???
    I also use ur solution bt it also didnt work,shows error on "Image".
    if there is any other solution u have then please help me thanx :)

    ReplyDelete
  18. In what format will the images in drawable be? Is it animated gif?

    ReplyDelete
  19. Nice Posting Keep it up.........thanks for sharing.........
    Free Download All Smart Phone Applications For your Smart Phones
    http://allphonesapps.blogspot.com

    ReplyDelete
  20. Hi, I have no errors but after run the application and set the Wallpaper, Long Press on Screen >Set Wallpaper > Home Screen > Live Wallpapers > select your Live wall paper,{but this application not found in my Wallpapers list }
    give me a solution i am using samsung galaxy core

    ReplyDelete
  21. Hi, I have no error but after run the application and set the Wallpaper.( Long Press on Screen ->Set Wallpaper -> Home Screen -> Live Wallpapers -> select your Live wall paper
    {""but i can not see the application on my Live Wallpapers list""
    the application see in application manager pls tell me what is problem iam using samsang galaxy core 4.2.1 jallibeen
    }

    ReplyDelete
  22. i m getting this error even i have created the mywallpaper.xml file
    Error: No resource found that matches the given name (at 'resource' with value '@xml/mywallpaper').

    ReplyDelete
  23. Ive followed the tutorial, step by step, to try to create a livewallpaper. But i have a problem that i cant find any solution. When i create the bitmap from the drawable, it allways returns null.

    In my case, the drawable is a shape in a xml file (inside drawable folder). This drawable is a rectangle, with a gradient. Is it not possible to draw on a canvas with this kind of source?

    Ps: Just tried with a png drawable, and it does work.

    Thanks in advance.

    ReplyDelete
  24. Ive followed the tutorial, step by step, to try to create a livewallpaper. But i have a problem that i cant find any solution. When i create the bitmap from the drawable, it allways returns null.

    In my case, the drawable is a shape in a xml file (inside drawable folder). This drawable is a rectangle, with a gradient. Is it not possible to draw on a canvas with this kind of source?

    Ps: Just tried with a png drawable, and it does work.

    Thanks in advance.

    ReplyDelete
  25. I have followed this tutorial step by step (99% sure) and anytime i try to create a bitmap from a drawable, i get a null object. In my case, my drawable is a shape from a xml (from drawable folder). This shape is a rectangle, with a gradient.

    Isnt it possible to do it this way?

    Thanks in advance.

    Ps: just tried with a png, and it works perfectly.

    ReplyDelete
  26. Dear
    your code this error occur
    MyWallpaperEngine() {
    // get the fish and background image references
    image1 = BitmapFactory.decodeResource(getResources(),R.drawable.fish);
    backgroundImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);
    x = -130; // initialize x position
    y = 200; // initialize y position

    }

    ReplyDelete
  27. Dear
    MyWallpaperEngine() {
    // get the fish and background image references
    image1 = BitmapFactory.decodeResource(getResources(),R.drawable.fish);
    backgroundImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);
    x = -130; // initialize x position
    y = 200; // initialize y position

    }

    your code error occur

    ReplyDelete
  28. First of all thanks for the post. I want to know how to set size for background image for different phones?
    I read your earlier post but cant get it. Can You please explain it in detail..

    Image backImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);
    bitmap = Bitmap.createScaledBitmap(backImage, c.getWidth(), c.getHeight(), true);

    where c is the object of canvas.
    and draw this bitmap.
    It will fill the full screen.

    ReplyDelete
  29. i do same but its not working....the code not contain any error also. please send me your program-me .

    ReplyDelete
  30. please send me your project code. my code is not working and also no error shows

    ReplyDelete
  31. I have just download the code and implement it in my mobile..really awesome. Thank you for sharing.

    Live Wallpaper Wildlife

    ReplyDelete
  32. I am not getting mylivewallpaper in LiveWallpaper List..

    ReplyDelete
    Replies
    1. Please give me a little detail of your problem, then only I will be able to help you..

      Delete
  33. Can you help me plz??
    there are 2 error in the source code they are below i describe
    1:LiveWallpaperService.java
    R.drawable.fish AND R.drawable.background
    2:mywallpaper.xml file
    the erorr was multiple annotation found at this line
    the line is below

    ReplyDelete
    Replies
    1. there could be some syntax error in mywallpaper.xml , try to correct it, or paste your mywallpaper.xml here.

      Delete
  34. I don't see the link to those 2 images.
    Where can I find these images?
    Thank you

    ReplyDelete
    Replies
    1. You can just download any imagee from NET and use it.

      Delete
  35. hello sir, Thanks for your post. I got a problem sir. I removed the background image and changed the code accordingly.
    I removed the activity_layout.xml from layout folder. I don't know whether its necessary. Then added xml folder and added your code in mywallpaper.xml. I changed the coding as follows to remove errors
    (added '+' ):




    then removed activity_main.java and added java code that you gave in the src folder.

    now i come to the troubling part. I installed it in my xperia m but when i try opening it,I got an error in my phone stating "Unfortunately, WallpaperService has stopped".
    Help me..

    ReplyDelete
  36. As such I did everything you had given there... Added images in drawable in the names you given... Then too is getting crashed when I try starting on my mobile.... Help...

    ReplyDelete
  37. I need slide show of images without any delay.. can you help?..

    ReplyDelete
  38. This comment has been removed by a blog administrator.

    ReplyDelete
  39. i do same but its not working....the code not contain any error also. but in am using mobile its give a one error that is force close.

    ReplyDelete
  40. i do same but its not working....the code not contain any error also. that app using in mobile force close window is to be displayed.

    ReplyDelete
  41. I did this and the code is not throwing any error. When i run the app, i am able to see the wall paper in emulator when i long press the home screen and select live wall papers. However after selecting the wall paper, it gives me msg, Unfortunately Live wall paper has stopped. Pls help. I am using samsung4.7 emulator

    ReplyDelete
  42. no errors in code, however if i select this wall paper in emulator it gives me msg: unfortunately live wall paper has stopped. M using samsung4.7 emulator

    ReplyDelete
  43. Sorry API level 19; target name: Android 4.4

    ReplyDelete
  44. i have followed your code.. deres no error and d app has installed successfully bt deres nothing showing in emulator i mean app is not showing in emulator

    ReplyDelete
  45. I have followed yor code n dere no error in app has installed successfully bt its not showing in emulator..

    ReplyDelete
  46. am i missing something? or you have not shared the Images?

    ReplyDelete
  47. constantly seeing classnotfound exception, how to solve it?

    ReplyDelete
  48. can you please help me.. im unable to run this, got classnotfound exception. please help

    ReplyDelete
    Replies
    1. Hello Krishna
      Please tell me for which class this error is coming.(paste the logcat error)
      Have you declared LiveWallpaperService class in manifest file.

      Delete
  49. okay i cleared the problem, thanq for the tutorial anyways!
    how can i add a touch event to this image?

    ReplyDelete
  50. hi.......thanx for tutorial its really nice........i hv a problem can you fix it?
    i want to retrive selected image from sd card with its path............
    thanx in advance...............

    ReplyDelete
  51. could it be that there is a limit on how large the pictures can be? I tried it with larger Pictures, 1000x2000 and it crashes very often both when selecting it and when it is set. Ironically it sometimes works without flaws. The Errors I get are either Low Memory or NullPointerExeption. Any Ideas? Thanks!

    ReplyDelete
  52. Can you please give a link to download this sample application source code?

    ReplyDelete
  53. Thanks. Good tutorial.

    ReplyDelete
  54. no activity found to lounch

    ReplyDelete
  55. i am getting an error in manifest.xml file. there is no activity tag , so that it is not finding any activity to launch. I have written a tag for activity but it is stopping unfortunately.

    ReplyDelete
  56. hi...
    how to add more than one fish in different position ?

    ReplyDelete
  57. Is there a way to add set wallpaper to a luncher page , to avoid ( Long Press on Screen ->Set Wallpaper -> HomeScreen -> Live Wallpapers -> select your Live wall paper)

    ReplyDelete
  58. How do i add fadein fadeout effect while drawing bitmap

    ReplyDelete
  59. if (visible)
    {
    handler.post(drawRunner);
    }
    else
    {
    handler.removeCallbacks(drawRunner);
    }
    }

    @Override
    public void onSurfaceDestroyed(SurfaceHolder holder)
    {
    super.onSurfaceDestroyed(holder);
    this.visible = false;
    handler.removeCallbacks(drawRunner);

    I have errors on remove callback and on .post

    as well as.. if (visible)
    {
    handler.postDelayed(drawRunner, 10); // delay 10 mileseconds
    }
    postdelayed?

    ReplyDelete
  60. I kept both the images with name "fish" and "background" in drawable folder. but it is not getting access...

    ReplyDelete
  61. Thanks for the marvelous posting! I definitely enjoyed reading it, you
    might be a great author. I wijll make certain too bookmark your blog and will come back from nnow on.
    I want to enmcourage that youu continue your geeat writing, have a nice holiday weekend!

    ReplyDelete
  62. Direito Administrativo Brasílico, 28ª edição.

    ReplyDelete
  63. I have to thank you forr the efforts you'veput in writing this
    blog. I am hoping to view the same high-grade
    blog posts by you in the future as well. In truth, your crreative writing abilities has inspired me to gget my own website now ;)

    ReplyDelete
  64. Contribuições de Melhoria de obras públicas".

    ReplyDelete
  65. Curso de direito tributário brasílico,6.

    ReplyDelete
  66. Thanks forr some other informative site. Where else could I am getting that type of ifo written in suh a perfect means?
    I've a project that I'm simply now working
    on, and I have been at the look out for such information.

    ReplyDelete
  67. This is a very good information. Thank you for sharing.
    bigolive

    ReplyDelete
  68. At this time I am going to do my breakfast, once having
    my breakfast coming yet again too read addittional news.

    ReplyDelete
  69. Mudanças Interestaduais para todo Brasil.

    ReplyDelete
  70. thanks for informative content and code by wallpapersly.com

    ReplyDelete
  71. Hi,
    Thanks for sharing the information with us it was very informative. https://hangup.in

    ReplyDelete