Android Alive Wallpaper. This tutorial describes the creation of alive wallpapers for Android. It is based on Eclipse iv.2, Java ane.6 and Android 4.ane (Ice Cream Sandwich).

ii. Overview

two.i. Alive Wallpapers

Live Wallpapers are blithe, interactive backgrounds for the Android dwelling house screen. A live wallpaper is like to other Android applications and can use most of the same functionality.

ii.2. How to create a live wallpaper

To create a live wallpaper, you need to create an XML file which describes your wallpaper. This file should contain a clarification of the awarding and tin contain a preview and a link to a preference activeness Activity which allow to customize the live wallpaper.

Y'all besides create a service which must extend the WallpaperService form. This course is the base of operations class for all live wallpapers in the organisation. Yous must implement the onCreateEngine() method and return an object of type android.service.wallpaper.WallpaperService.Engine. This objects handles the lifecycle events, animations and drawings of the wallpaper. The Engine class defines the life bike methods, as for instance onCreate(), onSurfaceCreated(), onVisibilityChanged(), onOffsetsChanged(), onTouchEvent() and onCommand().

The service requires the permission android.permission.BIND_WALLPAPER and must be registered via an intent-filter for the android.service.wallpaper.WallpaperService action.

Y'all should likewise enter in the AndroidManifest.xml file of the application that your awarding uses the android.software.live_wallpaper feature. This will prevent that your wallpaper can be installed on devices which practice non support live wallpapers.

ii.3. Intent to prepare the wallpaper

You tin use an Intent to set the Wallpaper.

                                      // Button to set the Wallpaper                    public                    void                    onClick                    (                    View                    view                    )                    {                    Intent                    intent                    =                    new                    Intent                    (                    WallpaperManager                    .                    ACTION_CHANGE_LIVE_WALLPAPER                    );                    intent                    .                    putExtra                    (                    WallpaperManager                    .                    EXTRA_LIVE_WALLPAPER_COMPONENT                    ,                    new                    ComponentName                    (                    this                    ,                    MyWallpaperService                    .                    class                    ));                    startActivity                    (                    intent                    );                    }                                  

3. Android Wallpaper Example

Create a new project called de.vogella.android.wallpaper. Do not create an action.

Create the /res/xml binder and create the mywallpaper.xml file.

                                  <?xml version="i.0" encoding="UTF-viii"?>                  <wallpaper                  xmlns:android=                  "http://schemas.android.com/apk/res/android"                  android:thumbnail=                  "@drawable/icon"                  android:description=                  "@cord/wallpaper_description"                  android:settingsActivity=                  "de.vogella.android.wallpaper.MyPreferencesActivity"                  />                              

This file contains a description of your wallpaper and a preview graphic. You tin can also enter a link to an activity which permit to configure the wallpaper. This resource file will be linked to from the AndroidManifest.xml. You could also include the "android:thumbnail attribute" which would betoken to a drawable which gives a smaller epitome of the running wallpaper.

Alter your AndroidManifest.xml to the post-obit to define your MyWallpaperService service. Also define the uses-characteristic.

                                  <?xml version="1.0" encoding="utf-8"?>                  <manifest                  xmlns:android=                  "http://schemas.android.com/apk/res/android"                  bundle=                  "de.vogella.android.wallpaper"                  android:versionCode=                  "1"                  android:versionName=                  "1.0"                  >                  <application                  android:icon=                  "@drawable/icon"                  android:label=                  "@string/app_name"                  >                  <service                  android:name=                  "MyWallpaperService"                  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:proper noun=                  "android.service.wallpaper"                  android:resource=                  "@xml/mywallpaper"                  >                  </meta-data>                  </service>                  <action                  android:proper name=                  ".MyPreferencesActivity"                  android:exported=                  "true"                  android:label=                  "@string/app_name"                  android:theme=                  "@android:manner/Theme.Light.WallpaperSettings"                  >                  </activity>                  <activeness                  android:name=                  ".SetWallpaperActivity"                  android:label=                  "@string/app_name"                  android:theme=                  "@android:style/Theme.Light.WallpaperSettings"                  >                  <intent-filter>                  <activity                  android:proper noun=                  "android.intent.activeness.Principal"                  />                  <category                  android:proper noun=                  "android.intent.category.LAUNCHER"                  />                  </intent-filter>                  </activity>                  </application>                  <uses-sdk                  android:minSdkVersion=                  "10"                  />                  <uses-feature                  android:proper noun=                  "android.software.live_wallpaper"                  android:required=                  "true"                  >                  </uses-feature>                  </manifest>                              

Nosotros create the MyPoint class to save the elements we have fatigued.

                                  package                  de                  .                  vogella                  .                  android                  .                  wallpaper                  ;                  public                  class                  MyPoint                  {                  String                  text                  ;                  private                  int                  x                  ;                  individual                  int                  y                  ;                  public                  MyPoint                  (                  String                  text                  ,                  int                  x                  ,                  int                  y                  )                  {                  this                  .                  text                  =                  text                  ;                  this                  .                  10                  =                  x                  ;                  this                  .                  y                  =                  y                  ;                  }                  }                              

Create a new activity. Create the prefs.xml preference file in the res/xml binder.

                                  <?                  xml                  version                  =                  "one.0"                  encoding                  =                  "utf-8"                  ?>                  <                  PreferenceScreen                  xmlns:                  android                  =                  "http://schemas.android.com/apk/res/android"                  >                  <                  CheckBoxPreference                  android:                  key                  =                  "touch"                  android:                  championship                  =                  "Enable Bear on"                  ></                  CheckBoxPreference                  >                  <                  EditTextPreference                  android:                  cardinal                  =                  "numberOfCircles"                  android:                  championship                  =                  "Number of Circles"                  ></                  EditTextPreference                  >                  </                  PreferenceScreen                  >                              

Create a new action called MyPreferencesActivity and the following class.

                                  package                  de                  .                  vogella                  .                  android                  .                  wallpaper                  ;                  import                  android.os.Parcel                  ;                  import                  android.preference.Preference                  ;                  import                  android.preference.Preference.OnPreferenceChangeListener                  ;                  import                  android.preference.PreferenceActivity                  ;                  import                  android.widget.Toast                  ;                  public                  grade                  MyPreferencesActivity                  extends                  PreferenceActivity                  {                  @Override                  protected                  void                  onCreate                  (                  Packet                  savedInstanceState                  )                  {                  super                  .                  onCreate                  (                  savedInstanceState                  );                  addPreferencesFromResource                  (                  R                  .                  xml                  .                  prefs                  );                  // add together a validator to the "numberofCircles" preference so that it just                  // accepts numbers                  Preference                  circlePreference                  =                  getPreferenceScreen                  ().                  findPreference                  (                  "numberOfCircles"                  );                  // add the validator                  circlePreference                  .                  setOnPreferenceChangeListener                  (                  numberCheckListener                  );                  }                  /**      * Checks that a preference is a valid numerical value      */                  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                  (                  MyPreferencesActivity                  .                  this                  ,                  "Invalid Input"                  ,                  Toast                  .                  LENGTH_SHORT                  ).                  show                  ();                  render                  simulated                  ;                  }                  };                  }                              

Create the following coding for the Wallpaper service.

                                  package                  de                  .                  vogella                  .                  android                  .                  wallpaper                  ;                  import                  java.util.ArrayList                  ;                  import                  java.util.List                  ;                  import                  android.content.SharedPreferences                  ;                  import                  android.graphics.Canvass                  ;                  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                  grade                  MyWallpaperService                  extends                  WallpaperService                  {                  @Override                  public                  Engine                  onCreateEngine                  ()                  {                  return                  new                  MyWallpaperEngine                  ();                  }                  private                  class                  MyWallpaperEngine                  extends                  Engine                  {                  individual                  final                  Handler                  handler                  =                  new                  Handler                  ();                  private                  concluding                  Runnable                  drawRunner                  =                  new                  Runnable                  ()                  {                  @Override                  public                  void                  run                  ()                  {                  draw                  ();                  }                  };                  private                  List                  <                  MyPoint                  >                  circles                  ;                  private                  Paint                  pigment                  =                  new                  Pigment                  ();                  private                  int                  width                  ;                  int                  height                  ;                  private                  boolean                  visible                  =                  true                  ;                  private                  int                  maxNumber                  ;                  individual                  boolean                  touchEnabled                  ;                  public                  MyWallpaperEngine                  ()                  {                  SharedPreferences                  prefs                  =                  PreferenceManager                  .                  getDefaultSharedPreferences                  (                  MyWallpaperService                  .                  this                  );                  maxNumber                  =                  Integer                  .                  valueOf                  (                  prefs                  .                  getString                  (                  "numberOfCircles"                  ,                  "4"                  ));                  touchEnabled                  =                  prefs                  .                  getBoolean                  (                  "bear on"                  ,                  false                  );                  circles                  =                  new                  ArrayList                  <                  MyPoint                  >();                  paint                  .                  setAntiAlias                  (                  true                  );                  pigment                  .                  setColor                  (                  Color                  .                  WHITE                  );                  pigment                  .                  setStyle                  (                  Paint                  .                  Manner                  .                  STROKE                  );                  paint                  .                  setStrokeJoin                  (                  Paint                  .                  Join                  .                  Round                  );                  paint                  .                  setStrokeWidth                  (                  ten                  f                  );                  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 = faux;             handler.removeCallbacks(drawRunner);         }          @Override         public void onSurfaceChanged(SurfaceHolder holder, int format,                 int width, int meridian) {             this.width = width;             this.meridian = height;             super.onSurfaceChanged(holder, format, width, tiptop);         }          @Override         public void onTouchEvent(MotionEvent event) {             if (touchEnabled) {                  float x = event.getX();                 float y = outcome.getY();                 SurfaceHolder holder = getSurfaceHolder();                 Sail canvas = naught;                 effort {                     canvas = holder.lockCanvas();                     if (canvas != cipher) {                         canvas.drawColor(Colour.Black);                         circles.clear();                         circles.add(new MyPoint(                                 Cord.valueOf(circles.size() + 1), x, y));                         drawCircles(canvas, circles);                      }                 } finally {                     if (canvas != null)                         holder.unlockCanvasAndPost(sheet);                 }                 super.onTouchEvent(event);             }         }          individual void draw() {             SurfaceHolder holder = getSurfaceHolder();             Canvas canvas = goose egg;             effort {                 canvas = holder.lockCanvas();                 if (canvas != null) {                     if (circles.size() >= maxNumber) {                         circles.articulate();                     }                     int x = (int) (width * Math.random());                     int y = (int) (acme * Math.random());                     circles.add(new MyPoint(String.valueOf(circles.size() + 1),                             x, y));                     drawCircles(canvas, circles);                 }             } finally {                 if (canvass != nil)                     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, Listing<MyPoint> circles) {             canvas.drawColor(Color.BLACK);             for (MyPoint point : circles) {                 sail.drawCircle(point.ten, point.y, 20.0f, paint);             }         }     }              

Create the post-obit Activity which should use a layout with one Button included. This Button should utilise the onClick property to bespeak to the onClick method.

                                  bundle                  de                  .                  vogella                  .                  android                  .                  wallpaper                  ;                  import                  android.app.Activeness                  ;                  import                  android.app.WallpaperManager                  ;                  import                  android.content.ComponentName                  ;                  import                  android.content.Intent                  ;                  import                  android.os.Bundle                  ;                  import                  android.view.View                  ;                  public                  class                  SetWallpaperActivity                  extends                  Activeness                  {                  @Override                  protected                  void                  onCreate                  (                  Packet                  savedInstanceState                  )                  {                  super                  .                  onCreate                  (                  savedInstanceState                  );                  setContentView                  (                  R                  .                  layout                  .                  main                  );                  }                  public                  void                  onClick                  (                  View                  view                  )                  {                  Intent                  intent                  =                  new                  Intent                  (                  WallpaperManager                  .                  ACTION_CHANGE_LIVE_WALLPAPER                  );                  intent                  .                  putExtra                  (                  WallpaperManager                  .                  EXTRA_LIVE_WALLPAPER_COMPONENT                  ,                  new                  ComponentName                  (                  this                  ,                  MyWallpaperService                  .                  class                  ));                  startActivity                  (                  intent                  );                  }                  }                              

If you lot start your application your application should allow to gear up the wallpaper. Your background should expect similar to the following screenshot. If you take Touch enabled via the preferences you tin click on the screen to remove the existing circles, too via the settings you can ascertain the number of circles which should exist displayed.

Live Wallpaper displayed