python-3.xkivypyjnius

Change Device Wallpaper in Python/Kivy


I have a simple app and,among other things, I need this app to be able to change the wallpaper of a device on Android.

Now, I've looked around on the net and pyjnius seems like the obvious choice. The problem now is I don't know the first thing about java but a quick google search produces the WallpaperManager as something I could use.

Here's the question: How do I implement that wallpaper manager functionality on my kivy app with pyjnius. Again, NOT a java dev so don't shoot


Solution

  • I don't know Java either but after examining some java examples i generated a solution. Don't forget to add SET_WALLPAPER permission to your buildozer.spec file. You also need to get storage permission to have this example work.

    from jnius import autoclass, cast
    
    PythonActivity = autoclass('org.kivy.android.PythonActivity')
    
    try:
        Environment = autoclass("android.os.Environment")
        path = Environment.getExternalStorageDirectory().toString()
        
        currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
        context = cast('android.content.Context', currentActivity.getApplicationContext())
        
        File = autoclass('java.io.File')
        file = File(path+"/test.jpg")
        
        BitmapFactory = autoclass('android.graphics.BitmapFactory')
        bitmap = BitmapFactory.decodeFile(file.getAbsolutePath())
        
        WallpaperManager = autoclass('android.app.WallpaperManager')
        manager = WallpaperManager.getInstance(context)
        manager.setBitmap(bitmap)
              
    except Exception as e:
        print(e)