Android Studio 壁纸是不设置一旦设置一个壁纸

ccgok5k5  于 2023-10-23  发布在  Android
关注(0)|答案(1)|浏览(130)

我有一个视频壁纸应用程序,我试图设置动态壁纸的第一次,它的工作正常。但第二次它不改变壁纸,除非我重新启动设备。
我也试过使用“wallpapermanager.clear”功能,但问题是如果用户不设置壁纸,以前的壁纸会自动删除。
我不想把前一个拿掉。

Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
vintent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
    new ComponentName(this, MyWallpaperService.class));
vstartActivity(intent);

try {
    WallpaperManager.getInstance(this).clear();
} catch (IOException e) {
    e.printStackTrace();
}
5kgi1eie

5kgi1eie1#

保存您的更改在SharedPreference您的壁纸类,即MyWallpaperService使用下面的代码,并根据您的需要修改,希望它的帮助. OnSharedPreferenceChangeMap使用保存数据以前和更新,你只需要设置条件时,你想更新
public void run(){

/**
 * Service Starting Hierarchy
 *      1) Service:         onCreate()
 *      2) Service:         onCreateEngine()
 *          i) Engine:              onCreate()
 *          ii) Engine:             onSurfaceCreated()
 *          iii) Engine:            onSurfaceChanged()
 *          iv) Engine:             onVisibilityChanged()
 *          v) Engine:              onTouchEvent()                  // if any
 *          vi) Engine:             onSurfaceDestroyed()
 *          iii) Engine:            onDestroy()
 *      3) Service:         onDestroy()
 */

override fun onCreateEngine(): Engine {
    return MyWallpaperEngine()
}

private inner class MyWallpaperEngine : Engine(), SharedPreferences.OnSharedPreferenceChangeListener {

    // A reference to our shared prefs;

    override fun onCreate(surfaceHolder: SurfaceHolder?) {
        super.onCreate(surfaceHolder)

        // Create an instance of CustomEngine
        val customEngine = MyWallpaperEngine()
       // Register the listener to start listening for shared preference changes
        customEngine.registerSharedPreferencesListener()

    }

    // Method to register the listener
    private fun registerSharedPreferencesListener() {
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        sharedPreferences.registerOnSharedPreferenceChangeListener(this)
    }

    // Method to unregister the listener
    private fun unregisterSharedPreferencesListener() {
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
    }

    override fun onDestroy() {
        super.onDestroy()

        // Unregister the shared preferences listener to avoid memory leaks
        unregisterSharedPreferencesListener()
    }
    override fun onSharedPreferenceChanged(
        sharedPreferences: SharedPreferences?,
        key: String?
    ) {
       //your Changes data 
       //Rest of Code
    }
}

}

相关问题