Showing posts with label Set Wallpaper Android. Show all posts
Showing posts with label Set Wallpaper Android. Show all posts

Saturday, 19 April 2014

Set Wallpaper Android

Define Object 

File    myFolder;
    File file;
    WallpaperManager wallpaperManager ;

In Oncreat

boolean success = false;
        myFolder = new File("/sdcard/Diwali/");
        if( myFolder.exists() ){
            Log.d("", "FOLDER EXISTS");
        }else{

            success = myFolder.mkdir();

            if( success ){
                // Do something on success

            } else {
                // Do something else on failure
                throw new RuntimeException("File Error in writing new folder");
            }
        }

On Click Set Wallpaper


                SetWallpaper();
               
                DisplayMetrics displaymetrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                int height = displaymetrics.heightPixels;
                int width = displaymetrics.widthPixels;
                img.setDrawingCacheEnabled(true);
                Bitmap bmScreen = img.getDrawingCache();
                Bitmap scaled = Bitmap.createScaledBitmap(bmScreen, width, height, true);
               
               
                File myDir = new File(""+myFolder);   
                myDir.mkdirs();
                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = "Image-"+ n +".jpg";
                 file = new File (myDir, fname);
                if (file.exists ()) file.delete ();
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    scaled.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.flush();
                    out.close();

                    wallpaperManager = WallpaperManager.getInstance(GalleryActivity.this.getApplicationContext());

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


Methods


private void SetWallpaper() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("Confirm");
        builder.setMessage("Set as Wallpaper ?");

        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // Do nothing but close the dialog
                applyWallpaperFromFile(file);
                dialog.dismiss();
            }

        });

        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
                dialog.dismiss();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
       
    }


    public static Bitmap decodeFile(File file, int reqWidth, int reqHeight){
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getPath(), options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(file.getPath(), options);    
    }
       
    private 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;
        }

        return inSampleSize;
    }  
   
    private void applyWallpaperFromFile(final File file)
    {
        Bitmap wallpaperImage = BitmapFactory.decodeFile(file.getPath());
        try {
            if((wallpaperManager.getDesiredMinimumWidth()>0)&&(wallpaperManager.getDesiredMinimumHeight()>0))
            {
                Bitmap blank = BitmapHelper.createNewBitmap(wallpaperManager.getDesiredMinimumWidth(), wallpaperManager.getDesiredMinimumHeight());
                Bitmap overlay = BitmapHelper.overlayIntoCentre(blank, wallpaperImage);

                wallpaperManager.setBitmap(overlay);

            }
            else
            {
                wallpaperManager.setBitmap(wallpaperImage);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                //Toast.makeText(FullSMSView.this,"Wallpaper set to:"+file.getName(), Toast.LENGTH_SHORT).show();
                Toast.makeText(GalleryActivity.this,"Set as a Wallpaper", Toast.LENGTH_SHORT).show();

            }
        });

    }
   
    public static class BitmapHelper {

        public static Bitmap overlayIntoCentre(Bitmap bmp1, Bitmap bmp2) {
            Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
            Canvas canvas = new Canvas(bmOverlay);
            canvas.drawBitmap(bmp1, new Matrix(), null);//draw background bitmap

            //overlay the second in the centre of the first
            //(may experience issues if the first bitmap is smaller than the second, but then why would you want to overlay a bigger one over a smaller one?!)
            canvas.drawBitmap(bmp2, (bmp1.getWidth()/2)-(bmp2.getWidth()/2), 0, null);

            return bmOverlay;
        }

        public static Bitmap createNewBitmap(int width, int height)
        {
                    //create a blanks bitmap of the desired width/height
            return Bitmap.createBitmap(width, height, Config.ARGB_8888);
        }
        }


Njoy the Code!!