Android Open Source - AndroidRandomWallpaper Service






From Project

Back to project page AndroidRandomWallpaper.

License

The source code is released under:

GNU General Public License

If you think the Android project AndroidRandomWallpaper listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.elbauldelprogramador.randomwallpaper;
/*w w  w .j  av a2s .co  m*/
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Locale;
import java.util.Random;

import android.app.IntentService;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.PowerManager;
import android.util.Log;

import com.elbauldelprogramador.randomwallpaper.activities.MainActivity;
import com.elbauldelprogramador.randomwallpaper.util.RWGlobal;

public class Service extends IntentService
{
  private static final String TAG = "RandomWallPaperService";
  private String sourceFolder;
  
    public Service() {
    super(TAG);
    this.sourceFolder = RWGlobal.defaultSourceFolder();
  }
    
    @Override
  protected void onHandleIntent(Intent intent) {
      PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
      if (pm.isScreenOn()){
        Log.d(MainActivity.TAG,"OnHandleIntent");  
        if (intent.hasExtra("path") 
            && intent.hasExtra("height") 
            && intent.hasExtra("width")){
          sourceFolder = intent.getExtras().getString("path");
          int height = intent.getExtras().getInt("height");
              int width = intent.getExtras().getInt("width");
              
              Log.d(MainActivity.TAG, "in onHandleIntent, path = " + sourceFolder +
                  ", Height = " + height + ", Width = " + width);
              
              if(RWGlobal.thereAreImages(sourceFolder))
                changeWallPaper(height, width);
              else
                RWGlobal.toast(getApplicationContext(), 
                    getApplicationContext().getResources().getString(R.string.service_no_images));
        }
      } else
        Log.w(MainActivity.TAG, "Phone screen is off, wallpaper will not be changed");
  }
    
  /**
   * 
   * @param options
   * @param reqWidth
   * @param reqHeight
   * @return int
   * @see http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
   */
  public static int calculateInSampleSize(BitmapFactory.Options options,
      int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

      // Calculate ratios of height and width to requested height and
      // width
      final int heightRatio = Math.round((float) height
          / (float) reqHeight);
      final int widthRatio = Math.round((float) width / (float) reqWidth);

      // Choose the smallest ratio as inSampleSize value, this will
      // guarantee
      // a final image with both dimensions larger than or equal to the
      // requested height and width.
      inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    Log.d(MainActivity.TAG, " in sample Size: " + inSampleSize);
    return inSampleSize;
  }
  
  /**
   * Choose a path to an image randomly
   * @return Path to file as String
   */
  private String getRandomFile(){
    File dir = new File(sourceFolder);
    FileFilter imagesFilter = new FileFilter() {
      
      @Override
      public boolean accept(File pathname) {
        String ext = pathname.getName();
        if( ext.toLowerCase(Locale.ENGLISH).endsWith("jpg") || 
          ext.toLowerCase(Locale.ENGLISH).endsWith(".jpeg") || 
          ext.toLowerCase(Locale.ENGLISH).endsWith(".png")){
          return true;
        }
        return false;
      }
    };
    File[] files = dir.listFiles(imagesFilter);
    Random generator = new Random(System.currentTimeMillis());
    int randomImage = generator.nextInt(files.length);
    Log.d(MainActivity.TAG, "PATH:" + files[randomImage].getAbsolutePath()
        + " Index: " + randomImage + " TOTAL: " + files.length);
    return files[randomImage].getAbsolutePath();
  }
  
  public static Bitmap decodeSampledBitmapFromFile(String path, int width, int height) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    //String imageType = options.outMimeType;

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    
    return BitmapFactory.decodeFile(path, options);
  }

  private void changeWallPaper(int h, int w){
    String path = getRandomFile();
    Bitmap bm = decodeSampledBitmapFromFile(path, w, h);

    try {
      WallpaperManager mywall = WallpaperManager.getInstance(this);
      Log.i(MainActivity.TAG, "Setting wallpaper to " + path);
      mywall.setBitmap(bm);
    } catch (IOException e) {
      Log.e(MainActivity.TAG, "Cannot set image as wallpaper", e);
    }
  }
}




Java Source Code List

com.elbauldelprogramador.randomwallpaper.Service.java
com.elbauldelprogramador.randomwallpaper.activities.AboutTheApp.java
com.elbauldelprogramador.randomwallpaper.activities.MainActivity.java
com.elbauldelprogramador.randomwallpaper.reveivers.AlarmReceiver.java
com.elbauldelprogramador.randomwallpaper.reveivers.OnBootReceiver.java
com.elbauldelprogramador.randomwallpaper.util.RWGlobal.java
com.elbauldelprogramador.randomwallpaper.util.SimpleFileExplorer.java
com.elbauldelprogramador.randomwallpaper.util.StrictModeWrapper.java