Android Creating Live Wallpaper


A ‘live wallpaper’ is a type of application that works on a mobile device using the Android operating system. The application works as a wallpaper – providing the background image for the home screen—but also works as a conventional application since it can provide user-interaction with the touch screen (allowing the image to change dynamically, for example) and access other hardware and software features within the device (accelerometer, GPS, network access, etc.).

Below tutorial explains you the steps to create first basic wall paper.  This could be a great start in your android development career.  For this development we are using eclipse IDE and Android SDK .

  1. To create a new project  go to  File-> New-> Android Project and now you can name it whatever convenient for you,  in this tutorial we will name it as LiveWallpaper.
  2. Please copy following code into manifest file
    <?xml version="1.0" encoding="utf-8"?>  
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
       package="com.example.LiveWallpaper" android:versionCode="1"  
       android:versionName="1.0">  
        <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">  
     
     
            <service android:name="MyWallpaperService" android:enabled="true"  
               android:permission="android.permission.BIND_WALLPAPER" android:label="Wallpaper Example ">  
                <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>  
            <activity android:label="@string/app_name" android:name=".LiveWallpaperActivity"  
               android:theme="@android:style/Theme.Light.WallpaperSettings"  
               android:exported="true">  
            </activity>  
        </application>  
        <uses-sdk android:minSdkVersion="10" />  
        <uses-feature android:name="android.software.live_wallpaper"  
           android:required="true"></uses-feature>  
     
    </manifest>
  3. In res directory create a folder and name it “xml”.  Now create a “xml” file, copy following code  and name it mywallpaper.xml
    <?xml version="1.0" encoding="UTF-8"?>  
    <wallpaper  
       android:settingsActivity="de.vogella.android.wallpaper.MyPreferencesActivity"  
       xmlns:android="http://schemas.android.com/apk/res/android"  
       android:description="@string/wallpaper_description"  
       android:thumbnail="@drawable/ic_launcher" />
  4. Create a new xml file, copy following code and name it prefs.xml
    <?xml version="1.0" encoding="utf-8"?>  
    <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">  
        <CheckBoxPreference android:key="touch"  
           android:title="Enable Touch"></CheckBoxPreference>  
        <EditTextPreference android:key="numberOfCircles"  
           android:title="Number of Circles"></EditTextPreference>  
    </PreferenceScreen>
  5. Create a new java file and name it MyPoints.java and add it to src.  Your tree should be src/MyPoints.java
    package com.example.LiveWallpaper;
    
    public class MyPoint {  
        public String text;  
        public float x;  
        public float y;  
     
        public MyPoint(String text, float x, float y) {  
            this.text = text;  
            this.x = x;  
            this.y = y;  
        }  
     
    }
  6. Now we have to create a service class so that the wallpaper application can run from background.  In a new file which we will name it as MyWallpaperService.java
    package com.example.LiveWallpaper;
    
    import java.util.ArrayList;  
    import java.util.List;  
     
    import android.content.SharedPreferences;  
    import android.graphics.Canvas;  
    import android.graphics.Color;  
    import android.graphics.Paint;  
    import android.os.Handler;  
    import android.preference.PreferenceManager;  
    import android.service.wallpaper.WallpaperService;  
    import android.view.MotionEvent;  
    import android.view.SurfaceHolder;  
     
    public class MyWallpaperService extends WallpaperService {  
     
        @Override  
        public Engine onCreateEngine() {  
            return new MyWallpaperEngine();  
        }  
     
        private class MyWallpaperEngine extends Engine {  
            private final Handler handler = new Handler();  
            private final Runnable drawRunner = new Runnable() {  
                @Override  
                public void run() {  
                    draw();  
                }  
     
            };  
            private List<MyPoint> circles;  
            private Paint paint = new Paint();  
            private int width;  
            int height;  
            private boolean visible = true;  
            private int maxNumber;  
            private boolean touchEnabled;  
     
            public MyWallpaperEngine() {  
                SharedPreferences prefs = PreferenceManager  
                        .getDefaultSharedPreferences(MyWallpaperService.this);  
                maxNumber = Integer  
                        .valueOf(prefs.getString("numberOfCircles", "10"));  
                touchEnabled = prefs.getBoolean("touch", false);  
                circles = new ArrayList<MyPoint>();  
                paint.setAntiAlias(true);
                paint.setColor(Color.GREEN);  
                paint.setStyle(Paint.Style.STROKE);  
                paint.setStrokeJoin(Paint.Join.ROUND);  
                paint.setStrokeWidth(10f);  
                handler.post(drawRunner);  
            }  
     
            @Override  
            public void onVisibilityChanged(boolean visible) {  
                this.visible = visible;  
                if (visible) {  
                    handler.post(drawRunner);  
                } else {  
                    handler.removeCallbacks(drawRunner);  
                }  
            }  
     
            @Override  
            public void onSurfaceDestroyed(SurfaceHolder holder) {  
                super.onSurfaceDestroyed(holder);  
                this.visible = false;  
                handler.removeCallbacks(drawRunner);  
            }  
     
            @Override  
            public void onSurfaceChanged(SurfaceHolder holder, int format,  
                    int width, int height) {  
                this.width = width;  
                this.height = height;  
                super.onSurfaceChanged(holder, format, width, height);  
            }  
     
            @Override  
            public void onTouchEvent(MotionEvent event) {  
                if (touchEnabled) {  
     
                    float x = event.getX();  
                    float y = event.getY();  
                    SurfaceHolder holder = getSurfaceHolder();  
                    Canvas canvas = null;  
                    try {  
                        canvas = holder.lockCanvas();  
                        if (canvas != null) {  
                            canvas.drawColor(Color.BLACK);  
                            circles.clear();  
                            circles.add(new MyPoint(  
                                    String.valueOf(circles.size() + 1), x, y));  
                            drawCircles(canvas, circles);  
     
                        }  
                    } finally {  
                        if (canvas != null)  
                            holder.unlockCanvasAndPost(canvas);  
                    }  
                    super.onTouchEvent(event);  
                }  
            }  
     
            private void draw() {  
                SurfaceHolder holder = getSurfaceHolder();  
                Canvas canvas = null;  
                try {  
                    canvas = holder.lockCanvas();  
                    if (canvas != null) {  
                        if (circles.size() >= maxNumber) {  
                            circles.clear();  
                        }  
                        int x = (int) (width * Math.random());  
                        int y = (int) (height * Math.random());  
                        circles.add(new MyPoint(String.valueOf(circles.size() + 1),  
                                x, y));  
                        drawCircles(canvas, circles);  
                    }  
                } finally {  
                    if (canvas != null)  
                        holder.unlockCanvasAndPost(canvas);  
                }  
                handler.removeCallbacks(drawRunner);  
                if (visible) {  
                    handler.postDelayed(drawRunner, 5000);  
                }  
            }  
     
            // Surface view requires that all elements are drawn completely  
            private void drawCircles(Canvas canvas, List<MyPoint> circles) {  
                canvas.drawColor(Color.BLACK);  
                for (MyPoint point : circles) {  
                    canvas.drawCircle(point.x, point.y, 20.0f, paint);  
                }  
            }  
        }  
     
    }
  7. Now, run for the output, Please follow following steps:
    • Please Create a project named LiveWallpaper, replicate the information as mentioned in image.

    Build Target: Android 4.0
    Application Name: LiveWallpaper
    Package Name: com. example. LiveWallpaper
    Activity Name: LiveWallpaperActivity
    Min SDK Version: 14

    • Open LiveWallpaperActivity.java file and write following code there:
      package com.example.LiveWallpaper;
      
      import android.os.Bundle;  
      import android.preference.Preference;  
      import android.preference.Preference.OnPreferenceChangeListener;  
      import android.preference.PreferenceActivity;  
      import android.widget.Toast;  
       
      public class LiveWallpaperActivity extends PreferenceActivity {  
          @Override  
          protected void onCreate(Bundle savedInstanceState) {  
              super.onCreate(savedInstanceState);  
              addPreferencesFromResource(R.xml.prefs);  
       
              // We want to add a validator to the number of circles so that it only  
              // accepts numbers  
              Preference circlePreference = getPreferenceScreen().findPreference(  
                      "numberOfCircles");  
       
              // Add the validator  
              circlePreference.setOnPreferenceChangeListener(numberCheckListener);  
          }  
       
              Preference.OnPreferenceChangeListener numberCheckListener = new OnPreferenceChangeListener() {  
       
              @Override  
              public boolean onPreferenceChange(Preference preference, Object newValue) {  
                  // Check that the string is an integer  
                  if (newValue != null && newValue.toString().length() > 0  
                          && newValue.toString().matches("\\d*")) {  
                      return true;  
                  }  
                  // If now create a message to the user  
                  Toast.makeText(LiveWallpaperActivity.this, "Invalid Input",  
                          Toast.LENGTH_SHORT).show();  
                  return false;  
              }  
          };  
      }
    • Compile and build the project.
    • You can see following output

Related posts:

About author

This article was written by admin

Admin has over twenty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles. Working presently as Development Manager in India. A firm Believer in Knowledge grows when it shared.

Comments

No Comments

Leave your comment

Your email address will not be published. Required fields are marked *