How to get android lock screen wallpaper?
Asked Answered
M

3

9

I use the code below to retrieve the android lock screen wallpaper on an android 8.1 phone:

WallpaperManager manager = WallpaperManager.getInstance(getActivity());
ParcelFileDescriptor pfd = manager.getWallpaperFile(WallpaperManager.FLAG_LOCK);
if (pfd == null) // pfd is always null for FLAG_LOCK, why?
    return;
Bitmap lockScreenWallpaper = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
// ...

I have granted the READ_EXTERNAL_STORAGE permission and set a lock screen wallpaper beforehand.

I run the demo on a real phone, and found the pfd is always null for FLAG_LOCK, so I cannot get the lock screen wallpaper. Please help fix the problem, thanks.

Metencephalon answered 21/12, 2018 at 8:51 Comment(4)
I have checked your code. It works well. Do you request the permission truly? Or only add it in manifest file? I think the issue comes from permission.Salamander
@Salamander I have added the permission in the manifest file and also granted it manually at the app info screen. I tested the code on LGE Nexus 5x 8.0 and Xiaomi Redmi note5 8.1, and both failed. Did you run the code on a real phone? Thanks.Metencephalon
Yes, I tested it on Samsung A5, OS 8.0Salamander
@Salamander I don't know why then, it failed on both my real phones. Could you check if there are some differences between our code? Or Just post main part of you code in a new answer? Thanks.Metencephalon
M
8

I find the answer myself, I hope it can help others with the same question.

The official docs for getWallpaperFile says: If no lock-specific wallpaper has been configured for the given user, then this method will return null when requesting FLAG_LOCK rather than returning the system wallpaper's image file.

The description is vague, at least not clear enough, what does it mean? If you set a photo as both lock screen and home screen wallpaper, the two share the same file, then by calling

ParcelFileDescriptor pfd = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_LOCK);

pfd will always be null, then you should get the lock screen wallpaper this way:

if (pfd == null)
    pfd = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM);

you will get the non-null pfd. This is the case no lock-specific wallpaper has been configured.

On the contrary, lock-specific wallpaper has been configured if you set a photo as lock screen wallpaper directly, wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM) will return a non-null value.

So this is the code I use to retrieve the lock screen wallpaper:

/**
 * please check permission outside
 * @return Bitmap or Drawable
 */
public static Object getLockScreenWallpaper(Context context)
{
    WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
    if (Build.VERSION.SDK_INT >= 24)
    {
        ParcelFileDescriptor pfd = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_LOCK);
        if (pfd == null)
            pfd = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM);
        if (pfd != null)
        {
            final Bitmap result = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());

            try
            {
                pfd.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            return result;
        }
    }
    return wallpaperManager.getDrawable();
}

Don't forget to add READ_EXTERNAL_STORAGE in the manifest file and grant it outside.

Metencephalon answered 29/12, 2018 at 7:2 Comment(0)
S
6

The code I was testing is similar to yours. I have tested it on Samsung A5 and LG Nexus 5X.

MainActivity.java

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    public static final int REQUEST_CODE_EXTERNAL_STORAGE = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            permission = Manifest.permission.READ_EXTERNAL_STORAGE;
        }

        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{permission}, REQUEST_CODE_EXTERNAL_STORAGE);
        } else {
            retrieveLockScreenWallpaper();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_EXTERNAL_STORAGE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    retrieveLockScreenWallpaper();
                }
            }
        }
    }

    @SuppressLint("MissingPermission")
    private void retrieveLockScreenWallpaper() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
            ParcelFileDescriptor descriptor = manager.getWallpaperFile(WallpaperManager.FLAG_LOCK);
            if (descriptor != null) {
                Bitmap bitmap = BitmapFactory.decodeFileDescriptor(descriptor.getFileDescriptor());
                ((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);
            }
        }
    }

}

manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="aminography.com.lockscreenapplication">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application

        ...

    </application>

</manifest>

.

Result on LGE Nexus 5X (Android 8.1.0, API 27):

enter image description here

Salamander answered 24/12, 2018 at 10:47 Comment(2)
Many thanks for your help at first. I copied all your code in my project, and found it did not work either, the ParcelFileDescriptor descriptor is always null, really frustrating.Metencephalon
@QLocker: Have you tried the same code in a new project on the same device?Salamander
S
0

If no lock-specific wallpaper has been configured for the given user, then this method will return null when requesting FLAG_LOCK rather than returning the system wallpaper's image file.

Are you sure you have a valid lock screen wallpaper set for the current user?

 /**
     * Get an open, readable file descriptor to the given wallpaper image file.
     * The caller is responsible for closing the file descriptor when done ingesting the file.
     *
     * <p>If no lock-specific wallpaper has been configured for the given user, then
     * this method will return {@code null} when requesting {@link #FLAG_LOCK} rather than
     * returning the system wallpaper's image file.
     *
     * @param which The wallpaper whose image file is to be retrieved.  Must be a single
     *     defined kind of wallpaper, either {@link #FLAG_SYSTEM} or
     *     {@link #FLAG_LOCK}.
     *
     * @see #FLAG_LOCK
     * @see #FLAG_SYSTEM
     */
    public ParcelFileDescriptor getWallpaperFile(@SetWallpaperFlags int which) {
        return getWallpaperFile(which, mContext.getUserId());
    }

There is a similar function in WallpaperManager openDefaultWallpaper in that if you want LOCK-SCREEN wallpaper you get null, always, as According to the code Factory-default lock wallpapers are not yet supported.

So in your case maybe you haven't set the Lock-Screen wallpaper. Just to test, Download any wallpaper app, and try to set a wallpaper, then use your earlier code, to get it.

/**
     * Open stream representing the default static image wallpaper.
     *
     * If the device defines no default wallpaper of the requested kind,
     * {@code null} is returned.
     *
     * @hide
     */
    public static InputStream openDefaultWallpaper(Context context, @SetWallpaperFlags int which) {
        final String whichProp;
        final int defaultResId;
        if (which == FLAG_LOCK) {
            /* Factory-default lock wallpapers are not yet supported
            whichProp = PROP_LOCK_WALLPAPER;
            defaultResId = com.android.internal.R.drawable.default_lock_wallpaper;
            */
            return null;
        }

You can check the code at : http://androidxref.com/8.1.0_r33/xref/frameworks/base/core/java/android/app/WallpaperManager.java#openDefaultWallpaper

Sham answered 28/12, 2018 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.