Geek Mentors

  • Home
  • Games
  • Geek Hub
    • Tutorial
    • Review
    • How to
    • Apps
    • Buzz Beez
    • E Books
  • Portfolio
  • ABOUT US
  • Services
  • Contact

Part1 – Android Free Wallpaper App from start to finish using Material Design

By Tech Desk on January 29, 2016 at 3:32 am

Part1 – Android Free Wallpaper App

10
3
6
3
5
14

This tutorial explains how to build your own Wallpaper App using Picasa Web Albums API. This article is based on the in-depth tutorial created by Ravi Tamada of AndroidHive. I have tried to use Android Material Design, RecyclerView and DrawerLayout in this tutorial because I have faced a couple of challenges because some of the APIs have been deprecated since that tutorial was written. I would also like to point out that I just started developing for Android and this is my very first Application. So if you see my approach is not right and need some improvement please let me know in the comments.

You can check out this App on Google Play: Wallpapers and Backgrounds HD

wallpaper-and-backgrounds-hd on Google play

Below is the video of the App in Action


 

Getting Started:

I will try to explain as we move forward but if you still need in-depth explanation you must check out

Android Building Free Wallpapers App – Part 1

Android Building Free Wallpapers App – Part 2

 

About Google’s Picasa Web Albums API:

As Ravi in the above tutorials explained that the major and difficult task in this app is building the server side components like an admin panel to manage your wallpaper data by providing file upload option and other things. For this you should also able to code in other technologies like HTML, CSS, JSP, PHP or MySQL which is again a difficult task for android beginners. Since Picasa web albums is free of cost and importantly it exposes an API (json and xml) for developers. So it will be ideal solution in the current scenario. You can go through Picasa Web Albums Data API to know more about the API’s exposed. We are specifically interested in following API calls for this app which doesn’t require any authentication as we perform read operations only on public albums.

1. Request a list of albums (username should be replaced with your Google username)

https://picasaweb.google.com/data/feed/api/user/username?kind=album&alt=json

2. List photos recently uploaded (username should be replaced with your Google username)

https://picasaweb.google.com/data/feed/api/user/username?kind=photo&alt=json

3. List photos in album (albumid should be replaced with actual album id which can find in albums response)

https://picasaweb.google.com/data/feed/api/user/username/albumid/albumid?alt=json

 

Adding wallpapers in Picasa Web Albums

Before starting the app, we’ll add few wallpapers in Picasa albums for testing. You can login into Picasa using your Google account. Follow below steps to create albums and wallpapers in Picasa web albums.

1. Login into Picasa. (If you are redirected to your Google+ account, click on Click here to go back to Picasa Web Albumsto navigate back to Picasa Web or go with Google+ if you are comfortable)

2. Click on upload and enter your album name. These albums act as wallpaper categories in our app which will be listed in navigation drawer menu. Example: Animals, Autumn, Beaches, Buildings, Colorful etc.,

3. Once you created the album, upload few wallpapers to the album. Make sure that you are uploading the wallpapers with good high resolution. I have used some artworks from the web and gave the proper credit in each image.

4. Now make the album visibility as Public by clicking on Edit link displayed on the right. Note: If you don’t make your album as public, it will not be accessible via your android app. In other words you can’t see the album in the json response.

5. Follow 2nd, 3rd and 4th steps to create few more albums and wallpapers.

Creating New Project

1. In Android Studio, go to File → New Project and fill all the details required to create a new project. When it prompts to select a default activity, select Blank Activity and proceed. 2. Open build.gradle located under your app module and add below dependencies. After adding the dependencies, goto Build → Rebuild Project to download required libraries.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.mcxiaoke.volley:library:1.+'
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.android.support:support-v4:23.1.1'
}

2. Now add below resource values in colors.xml, styles.xml and strings.xml. These values will be used in various places in the project.

Also, download the resources and paste these in res → drawable.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#455a64</color>
    <color name="colorPrimaryDark">#32424a</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#000000</color>
    <color name="colorAccent">#FF80AB</color>
    <color name="counter_text_bg">#626262</color>
    <color name="counter_text_color">#c5c4c4</color>
    <color name="black">#000000</color>
    <color name="grid_bg">#000000</color>
    <color name="grid_item_bg">#1a1b1d</color>
    <color name="action_bar">#141416</color>
    <color name="action_bar_title">#ffffff</color>
    <color name="white">#ffffff</color>
    <color name="settings_label">#323232</color>
</resources>

 

<resources>
    <!-- Base application theme. -->

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

<style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>

 

<resources>
    <string name="app_name">WallpaperFreeApp</string>
    <string name="action_settings">Settings</string>
    <string name="action_rating">Rate Us</string>
    <string name="action_about">About</string>
    <string name="action_set_as_wallpaper">Set As Wallpaper</string>
    <string name="action_download">Download</string>
    <string name="action_share">Share</string>
    <string name="action_report">Report</string>

    <string name="action_search">Search</string>
    <string name="drawer_open">Open</string>
    <string name="drawer_close">Close</string>

    <string name="nav_drawer_recently_added">Recently Added</string>
    <string name="toast_saved">Wallpapaer saved to #</string>
    <string name="toast_saved_failed">Sorry! Failed to save wallpaper</string>
    <string name="toast_wallpaper_set">Wallpapaer updated!</string>
    <string name="toast_wallpaper_set_failed">Sorry! Unable to set wallpapaer</string>
    <string name="splash_error">Unable to download wallpapers. Verify your google\'s user name in settings or device doesn\'t have internet connection!</string>
    <string name="set_wallpaper">Set</string>
    <string name="download_wallpaper">Download</string>
    <string name="msg_unknown_error">Sorry! Unknown error occurred.</string>
    <string name="msg_wall_fetch_error">Sorry! Unable to fetch wallpaper(s). Verify app settings or device doesn\'t have internet connection.</string>
    <string name="toast_enter_google_username">Please enter google username</string>
    <string name="toast_enter_valid_grid_columns">Please enter valid number of columns</string>
    <string name="toast_enter_gallery_name">Please enter gallery directory name</string>
    <string name="lbl_google_username">Google username</string>
    <string name="lbl_no_grid_columns">Number of grid columns</string>
    <string name="lbl_gallery_name">Gallery directory name</string>
    <string name="lbl_btn_save">Save</string>
    <string name="lbl_btn_clear_cache">Clear Cache</string>
    <string name="lbl_btn_cache_size">Show Cache Size</string>
</resources>

In order to apply the theme, open AndroidManifest.xml and make sure that the android:theme attribute of <application> tag looks like below

android:theme="@style/AppTheme"

and modify the android:theme attribute of <activity> tag

android:theme="@style/AppTheme.NoActionBar"

So after applying the theme, your AndroidManifest.xml should look like below.

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.geekmentors.wallpaperfreeapp" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Now create a package named app under src folder. Right Click on src → New → Package.

Now create AppConst.java in app package. All the app configuration like google username, picasa api urls, gallery directory name and other static variables goes in this class.


package com.geekmentors.wallpaperfreeapp.app;

public class AppConst {
    // Number of columns of Grid View
    // by default 2 but user can configure this in settings activity
    public static final int NUM_OF_COLUMNS = 2;

    // Gridview image padding
    public static final int GRID_PADDING = 0; // in dp

    // Gallery directory name to save wallpapers
    public static final String SDCARD_DIR_NAME = "Awesome Wallpapers";

    // Picasa/Google web album username
    public static final String PICASA_USER = "freewallpapersapp";

    // Public albums list url
    public static final String URL_PICASA_ALBUMS = "https://picasaweb.google.com/data/feed/api/user/_PICASA_USER_?kind=album&alt=json";

    // Picasa album photos url
    public static final String URL_ALBUM_PHOTOS = "https://picasaweb.google.com/data/feed/api/user/_PICASA_USER_/albumid/_ALBUM_ID_?alt=json";

    // Picasa recenlty added photos url
    public static final String URL_RECENTLY_ADDED = "https://picasaweb.google.com/data/feed/api/user/_PICASA_USER_?kind=photo&alt=json";
}

 

Volley Library

To make calls to Picasa API we are going to use Volley Library instead of using the java library mentioned in the documentation. In this project it plays a major role in caching the images.

Remember? We have earlier added the dependency for the volley library

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.mcxiaoke.volley:library:1.+'
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.android.support:support-v4:23.1.1'
}

That’s really all there is to it, you can now read any Volley docs about how the library actually works and directly import the classes as though you wrote them yourself.

Now create a package named utils under src folder. Right Click on src ⇒ New ⇒ Package.

Create LruBitmapCache.java and paste the below code. This class used to keep the volley cached objects on the disk.

package com.geekmentors.wallpaperfreeapp.utils;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruBitmapCache extends LruCache<String, Bitmap> implements
        ImageCache {
    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        return cacheSize;
    }

    public LruBitmapCache() {
        this(getDefaultLruCacheSize());
    }

    public LruBitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}

Now create a package named picasa.model under src folder. Create two classes named Category.java and Wallpaper.java under picasa.model package. These POJO classes will be useful while parsing the json data fetched from Picasa.

 

package com.geekmentors.wallpaperfreeapp.picasa.model;

public class Category {
    public String id, title, photoNo;

    public Category() {
    }

    public Category(String id, String title, String photoNo) {
        this.id = id;
        this.title = title;
        this.photoNo = photoNo;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPhotoNo() {
        return photoNo;
    }

    public void setPhotoNo(String photoNo) {
        this.photoNo = photoNo;
    }
}

 

package com.geekmentors.wallpaperfreeapp.picasa.model;

import java.io.Serializable;

public class Wallpaper implements Serializable {
    private static final long serialVersionUID = 1L;
    private String url, photoJson;
    private int width, height;

    public Wallpaper() {
    }

    public Wallpaper(String photoJson, String url, int width, int height) {
        this.photoJson = photoJson;
        this.url = url;
        this.width = width;
        this.height = height;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getPhotoJson() {
        return photoJson;
    }

    public void setPhotoJson(String photoJson) {
        this.photoJson = photoJson;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }
}

 

Create another class named AppController.java under app package. This class extends fromApplication and this is a singleton class which initializes volley’s core objects and few other classes those can be used across the app.

 

package com.geekmentors.wallpaperfreeapp.app;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.geekmentors.wallpaperfreeapp.utils.LruBitmapCache;

import java.io.File;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    LruBitmapCache mLruBitmapCache;

    private static AppController mInstance;
    private PrefManager pref;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        pref = new PrefManager(this);

    }

    public static synchronized AppController getInstance() {

        return mInstance;
    }

    public PrefManager getPrefManger() {
        if (pref == null) {
            pref = new PrefManager(this);
        }

        return pref;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            getLruBitmapCache();
            mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
        }

        return this.mImageLoader;
    }

    public LruBitmapCache getLruBitmapCache() {
        if (mLruBitmapCache == null)
            mLruBitmapCache = new LruBitmapCache();
        return this.mLruBitmapCache;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

}

Create another class named PrefManager.java under utils package. This class takes care of storing the data in Shared Preferences. The data like google username, picasa wallpaper categories, gallery name and other things will be stored in shared preferences.

 

package com.geekmentors.wallpaperfreeapp.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.geekmentors.wallpaperfreeapp.app.AppConst;
import com.geekmentors.wallpaperfreeapp.picasa.model.Category;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class PrefManager {
    private static final String TAG = PrefManager.class.getSimpleName();

    // Shared Preferences
    SharedPreferences pref;

    // Editor for Shared preferences
    SharedPreferences.Editor editor;

    // Context
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Sharedpref file name
    private static final String PREF_NAME = "AwesomeWallpapers";

    // Google's username
    private static final String KEY_GOOGLE_USERNAME = "google_username";

    // No of grid columns
    private static final String KEY_NO_OF_COLUMNS = "no_of_columns";

    // Gallery directory name
    private static final String KEY_GALLERY_NAME = "gallery_name";

    // gallery albums key
    private static final String KEY_ALBUMS = "albums";

    public PrefManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);

    }

    /**
     * Storing google username
     * */
    public void setGoogleUsername(String googleUsername) {
        editor = pref.edit();

        editor.putString(KEY_GOOGLE_USERNAME, googleUsername);

        // commit changes
        editor.commit();
    }

    public String getGoogleUserName() {
        return pref.getString(KEY_GOOGLE_USERNAME, AppConst.PICASA_USER);
    }

    /**
     * store number of grid columns
     * */
    public void setNoOfGridColumns(int columns) {
        editor = pref.edit();

        editor.putInt(KEY_NO_OF_COLUMNS, columns);

        // commit changes
        editor.commit();
    }

    public int getNoOfGridColumns() {
        return pref.getInt(KEY_NO_OF_COLUMNS, AppConst.NUM_OF_COLUMNS);
    }

    /**
     * storing gallery name
     * */
    public void setGalleryName(String galleryName) {
        editor = pref.edit();

        editor.putString(KEY_GALLERY_NAME, galleryName);

        // commit changes
        editor.commit();
    }

    public String getGalleryName() {
        return pref.getString(KEY_GALLERY_NAME, AppConst.SDCARD_DIR_NAME);
    }

    /**
     * Storing albums in shared preferences
     * */
    public void storeCategories(List<Category> albums) {
        editor = pref.edit();
        Gson gson = new Gson();

        Log.d(TAG, "Albums: " + gson.toJson(albums));

        editor.putString(KEY_ALBUMS, gson.toJson(albums));

        // save changes
        editor.commit();
    }

    /**
     * Fetching albums from shared preferences. Albums will be sorted before
     * returning in alphabetical order
     * */
    public List<Category> getCategories() {
        List<Category> albums = new ArrayList<Category>();

        if (pref.contains(KEY_ALBUMS)) {
            String json = pref.getString(KEY_ALBUMS, null);
            Gson gson = new Gson();
            Category[] albumArry = gson.fromJson(json, Category[].class);

            albums = Arrays.asList(albumArry);
            albums = new ArrayList<Category>(albums);
        } else
            return null;

        List<Category> allAlbums = albums;

        // Sort the albums in alphabetical order
        Collections.sort(allAlbums, new Comparator<Category>() {
            public int compare(Category a1, Category a2) {
                return a1.getTitle().compareToIgnoreCase(a2.getTitle());
            }
        });

        return allAlbums;

    }

    /**
     * Comparing albums titles for sorting
     * */
    public class CustomComparator implements Comparator<Category> {
        @Override
        public int compare(Category c1, Category c2) {
            return c1.getTitle().compareTo(c2.getTitle());
        }
    }

}

 

Create another class named Utils.java under utils package. This class contains few helper methods.

 

package com.geekmentors.wallpaperfreeapp.utils;

import android.app.WallpaperManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.geekmentors.wallpaperfreeapp.R;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;

public class Utils {
    private String TAG = Utils.class.getSimpleName();
    private Context _context;
    private PrefManager pref;

    // constructor
    public Utils(Context context) {
        this._context = context;
        pref = new PrefManager(_context);
    }

    /*
     * getting screen width
     */
    @SuppressWarnings("deprecation")
    public int getScreenWidth() {
        int columnWidth;
        WindowManager wm = (WindowManager) _context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        final Point point = new Point();
        try {
            display.getSize(point);
        } catch (java.lang.NoSuchMethodError ignore) {
            // Older device
            point.x = display.getWidth();
            point.y = display.getHeight();
        }
        columnWidth = point.x;
        return columnWidth;
    }

    public void reportImage(Bitmap bitmap)
    {
        File myDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                pref.getGalleryName());

        myDir.mkdirs();
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Wallpaper-" + n + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists())
            file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

            Uri uri = getImageContentUri(_context,file);
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(_context);
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setType("text/html");
            intent.setData(Uri.parse("mailto:" + "info@geekmentors.com"));
            intent.putExtra(Intent.EXTRA_SUBJECT, "Wallpaper HD: Report Image");
            intent.putExtra(Intent.EXTRA_TEXT, "Write Your Report Below...");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            Intent chooserIntent = Intent.createChooser(intent,
                    "Report Via");
            chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            try {
                _context.startActivity(chooserIntent);
            }catch (Exception e)
            {
                e.printStackTrace();
            }

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

        }
    }

    public void shareImage(Bitmap bitmap, CoordinatorLayout coordinatorLayout)
    {
        File myDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                pref.getGalleryName());

        myDir.mkdirs();
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Wallpaper-" + n + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists())
            file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

            Uri uri = getImageContentUri(_context,file);

            // final Intent shareIntent = new Intent(Intent.ACTION_SEND);
            // shareIntent.setType("image/jpg");
            //  shareIntent.putExtra(Intent.EXTRA_STREAM, uri.fromFile(file));

            Intent wall_intent =  new Intent(Intent.ACTION_SEND);
            wall_intent.setType("image/*");
            wall_intent.putExtra("mimeType", "image/*");
            wall_intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            Intent chooserIntent = Intent.createChooser(wall_intent,
                    "Share Using");
            chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            try {
                _context.startActivity(chooserIntent);
            }catch (Exception e)
            {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
            Snackbar snackbar = Snackbar
                    .make(coordinatorLayout, _context.getString(R.string.toast_wallpaper_set_failed), Snackbar.LENGTH_SHORT);
            View sbView = snackbar.getView();
            TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
            textView.setTextColor(Color.YELLOW);
            snackbar.show();
        }

    }
    public void saveImageToSDCard(Bitmap bitmap, CoordinatorLayout coordinatorLayout) {
        File myDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                pref.getGalleryName());

        myDir.mkdirs();
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Wallpaper-" + n + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists())
            file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Snackbar snackbar = Snackbar
                    .make(coordinatorLayout,
                            _context.getString(R.string.toast_saved).replace("#",
                                    "\"" + pref.getGalleryName() + "\""), Snackbar.LENGTH_SHORT);
            View sbView = snackbar.getView();
            TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
            textView.setTextColor(Color.YELLOW);
            snackbar.show();
            Log.d(TAG, "Wallpaper saved to: " + file.getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
            Snackbar snackbar = Snackbar
                    .make(coordinatorLayout, _context.getString(R.string.toast_saved_failed), Snackbar.LENGTH_SHORT);
            View sbView = snackbar.getView();
            TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
            textView.setTextColor(Color.YELLOW);
            snackbar.show();
        }
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    public void setAsWallpaper(Bitmap bitmap, CoordinatorLayout coordinatorLayout) {

        File myDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                pref.getGalleryName());

        myDir.mkdirs();
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Wallpaper-" + n + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists())
            file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

            Uri uri = getImageContentUri(_context,file);
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(_context);
            //Intent intent = new Intent(wallpaperManager.getCropAndSetWallpaperIntent(uri));
            //_context.startActivity(intent);
            Intent wall_intent =  new Intent(Intent.ACTION_ATTACH_DATA);
            wall_intent.setDataAndType(uri, "image/*");
            wall_intent.putExtra("mimeType", "image/*");
            Intent chooserIntent = Intent.createChooser(wall_intent,
                    "Set As");
            chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                _context.startActivity(chooserIntent);
            }catch (Exception e)
            {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
            Snackbar snackbar = Snackbar
                    .make(coordinatorLayout, _context.getString(R.string.toast_wallpaper_set_failed), Snackbar.LENGTH_SHORT);
            View sbView = snackbar.getView();
            TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
            textView.setTextColor(Color.YELLOW);
            snackbar.show();
        }
    }
}

Let’s run the app and test it once. You should see something similar to the below screenshot

wallpaper_home
Now we have all the required classes in place. So let’s start adding one by one component to the app in

2nd Part of the Tutorial.

 

 

Download the Source Files

download

 

Update:

As of March 15, 2016, Google will no longer be supporting the Picasa desktop application, that’s why the response for Recently Updated Album has stopped coming from the API. The API will still support other functions, including reading photos, reading albums, reading photos in albums, and uploading new photos. Although these operations will continue to be supported and the protocol will remain the same, the content included in the responses and the operation behavior may change. Google will update the documentation on its site with specifics on the changes in March.
Read other important Picasa updates here.
Also, I have modified the code to load first album in the album list

 

Updated Code:

download
 

Check out our new tutorial:


Implement an Android Navigation Drawer with MaterialDrawer in less than 10 min
 

comments

Latest Tutorial

Android “Rate This App” Dialog tutorial

Apr 24, 2018 10986
  Today I will show you how to integrate the Rate This App dialog in an Android app. You must have seen that there are several application...
Implement an Android
Mar 2, 2018 1610
Integration of Fabri
Apr 10, 2016 64

Latest Reviews

Review: Duet Display App turns your iPad into extra display.

4279
Many PC/Mac owners also own an iPad and Duet App allows using the iPad as an extra monitor for the PC/Mac. Duet App's team which includes an Ex App...
DISCLAIMER ADVERTISE PRIVACY FEEDBACK CONTACT US
© Copyright 2015 Geek Mentors Studios Pvt Ltd. All Rights Reserved • Developed by Coravity Infotech