1

I am creating app to set image as wallpaper. I am using following code to fix image in every screen. The code is working fine. Image fit properly. But I have one problem if I play any game and then back to home screen or I restart my device then size of wallpaper zoom. I want to stop this. I want image size fit as it is on first time when I set wallpaper from my android app.

Here's Code-

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.full_image);
        face = Typeface.createFromAsset(getAssets(), "fonts/ABEAKRG.TTF");
        Intent i = getIntent();
        position = i.getExtras().getInt("id");        
        full = (LinearLayout) findViewById(R.id.full);
        btn = (Button)findViewById(R.id.btn);
        btn.setTypeface(face);
        btn.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View arg0) { 
             DisplayMetrics metrics = new DisplayMetrics(); 
             getWindowManager().getDefaultDisplay().getMetrics(metrics);
             int height = metrics.heightPixels; 
             int width = metrics.widthPixels;
             Bitmap tempbitMap = BitmapFactory.decodeResource(getResources(), mThumbId[position]);
             Bitmap bitmap = Bitmap.createScaledBitmap(tempbitMap,width,height, true);
             WallpaperManager wallpaperManager = WallpaperManager.getInstance(FullImageActivity.this); 
             wallpaperManager.setWallpaperOffsetSteps(1, 1);
             wallpaperManager.suggestDesiredDimensions(width, height);
             try {
               wallpaperManager.setBitmap(bitmap);
               Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_SHORT).show();
               } catch (IOException e) {
               e.printStackTrace();
             }
        }});
        changeBackground();
        ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
        full.setOnTouchListener(activitySwipeDetector);
    }



    private void changeBackground(){
        full.setBackgroundResource(mThumbId[position]);
   }

Thanks in advance.

John R
  • 2,078
  • 8
  • 35
  • 58

4 Answers4

3

Here is the code segment working for that

The MainActivity.java Code

The BootReceiver.java For Setting Wallpaper after boot completed..Code

And The Manifest.xml For setting Permissions..Code

Thanks

PankajSharma
  • 1,529
  • 14
  • 27
2

yesterday i have done this task..getting image from either gallery or through camera and set that as wall paper. for this i did like this. First get the image from gallery or camera. second compress or rescale it properly according to your need. third save that image in sharedpreferences so that if image is deleted from gallery or phone memory even in that case also it will be as it is a wall paper. finally set the image as wall paper in onCreate Method of activity .

public class Util {


public static final String PREFERENCES_NAME = "prefs";
public static SharedPreferences getSharedPreference(Context context) {
    return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
    } 
public static String getBackgroundImagePath(Context context) {
    return getSharedPreference(context).getString("imagepath","");
}

public static void setBackgroundImagePath(Context context, String path) {
    Editor edit = getSharedPreference(context).edit();
    edit.putString("imagepath", path);
    edit.commit();
}

}

call this setBackgroundImagePath method from activity by passing string path and context.like this //your image path

 String path = "";
 Util.setBackgroundImagePath(getApplicationContext(), path);

from onCreate() of activity,

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.full_image);
    face = Typeface.createFromAsset(getAssets(), "fonts/ABEAKRG.TTF");
    Intent i = getIntent();
    position = i.getExtras().getInt("id");        
    full = (LinearLayout) findViewById(R.id.full);
    btn = (Button)findViewById(R.id.btn);
    btn.setTypeface(face);
 Bitmap path = StringToBitMap(Util.getBackgroundImagePath(getApplicationContext()));
    if (path != null) {
        full.setBackgroundDrawable(new BitmapDrawable((path))); 
    }else {
        full.setBackgroundDrawable(R.drawable.defaultImage);
    }
    btn.setOnClickListener(new Button.OnClickListener(){
    @Override
    public void onClick(View arg0) { 
         DisplayMetrics metrics = new DisplayMetrics(); 
         getWindowManager().getDefaultDisplay().getMetrics(metrics);
         int height = metrics.heightPixels; 
         int width = metrics.widthPixels;
         Bitmap tempbitMap = BitmapFactory.decodeResource(getResources(), mThumbId[position]);
         Bitmap bitmap = Bitmap.createScaledBitmap(tempbitMap,width,height, true);
     full.setBackgroundDrawable(new BitmapDrawable((bitmap)));  
         String image_path = BitMapToString(bitmap);
         Util.setBackgroundImagePath(getApplicationContext(),image_path);
         WallpaperManager wallpaperManager= WallpaperManager.getInstance(FullImageActivity.this); 
         wallpaperManager.setWallpaperOffsetSteps(1, 1);
         wallpaperManager.suggestDesiredDimensions(width, height);
         try {
           wallpaperManager.setBitmap(bitmap);
           Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_SHORT).show();
           } catch (IOException e) {
           e.printStackTrace();
         }
    }});
    ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
    full.setOnTouchListener(activitySwipeDetector);

public Bitmap StringToBitMap(String encodedString){
    try{
        byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
        Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return bitmap;
    }catch(Exception e){
        e.getMessage();
        return null;
    }
}
public String BitMapToString(Bitmap bitmap){
    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte [] b=baos.toByteArray();
    String temp=Base64.encodeToString(b, Base64.DEFAULT);
    return temp;

} }

here i am setting background to layout if you have queries .. ask hope this helps you

GvSharma
  • 2,632
  • 1
  • 24
  • 30
  • I know I have to use sharedpreferences but dont know how to save image in sharedpreferences. Please tell me how to save? – John R Apr 16 '14 at 05:05
  • This code is little confusing for me. Can you please tell me where I have to add this code in my code? See update. – John R Apr 16 '14 at 05:37
  • Can you please tell me where I have to add this code in my code? – John R Apr 16 '14 at 08:35
  • I am getting error on return getSharedPreference(context).getString("imagepath",""); in utill class. – John R Apr 16 '14 at 09:21
  • its showing in solution create getSharedPreference method. – John R Apr 16 '14 at 09:21
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/50767/discussion-between-john-r-and-gvsharma) – John R Apr 16 '14 at 09:23
2

Try this to set the image as wallpaper

   try {
        WallpaperManager myWallpaperManager = WallpaperManager
                .getInstance(context);

        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int fullWidth = size.x;
        int fullHeight = size.y;

        // int fullWidth = wManager.getDesiredMinimumWidth();
        // int fullHeight = wManager.getDesiredMinimumHeight();

        Log.d("Debug", Integer.toString(fullWidth));
        Log.d("Debug", Integer.toString(fullHeight));

        Bitmap bitmap = BitmapFactory.decodeStream(getResources()
                .openRawResource(R.drawable.hello));

        Bitmap bitmapResized = Bitmap.createScaledBitmap(bitmap, fullWidth,
                fullHeight, true);
        myWallpaperManager.suggestDesiredDimensions(
                bitmapResized.getWidth(), bitmapResized.getHeight());

        myWallpaperManager.setBitmap(bitmapResized);

    } catch (IOException e) {
        e.printStackTrace();
    }

where the image is hello(R.drawable.hello)...

Lal
  • 14,726
  • 4
  • 45
  • 70
2

Some time ago I started developing an app to change the wallpaper Automatically. I didn't have the problems you mention. The key code is bellow, maybe it helps you.

The only difference I think is that I pick a wallpaper randomly in getRandomFile. Maybe is more easy to you check the entire app in gitHub, Although the class who changes the wallpaper is this

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);
    }
}

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);
}
/**
 * 
 * @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;
}
Alejandro Alcalde
  • 5,990
  • 6
  • 39
  • 79