3.2rc0 Android Live Wallpaper?

Greetings everyone,

I’m interested in using Cocos v3.2 for android live wallpapers but have run into a problem. I have found several good references for launching cocos as a wallpaper…



http://esotericsoftware.com/forum/viewtopic.php?f=5&t=1937

This approach works fine for 2.2.4 but fails in 3.2. Specifically the compiler complains that it requires Activity as a parameter for Cocos2dxHelper.init(). I am not an Android/Java developer but it appears that Cocos2dxHelper.init() has changed from taking a Context as a parameter to a Activity. I assume this worked in 2.2.4 because the WallpaperService class and the Activity class both share the same base Context class, but this is not the case 3.2. Glancing at Cocos2dxHelper.java it appears this change has been made throughout the interface so I couldn’t think of a quick way to patch it.

The question is is there a simple way to make this work in 3.2 or should I stick with 2.2.4 in the hopes that someone will someday add wallpaper support to 3.x?

Any advice is greatly appreciated :smile:

1 Like

Also interested in helping :diamond_shape_with_a_dot_inside:

I might be a little naive, can someone explain to me the obsession with “live wallpaper” apps recently? It seems to be Android only that there is this interest too.

Why is this so popular that multiple’s of developers are looking to do this?

Can’t speak for anyone else but for me it seems like a great way to play with the engine and art ideas without getting into full on game development. It also seems possible to get art out to the public while making a little money from advertising if done properly, but I haven’t seen any individuals actually doing this successfully AFAIK.

IOS 7 introduced “Dynamic Wallpaper” which is currently not open to developers (without jailbreaking) but does imply that it could be someday. I’ve also heard rumors that live wallpapers could be coming for Blackberry and Windows Phone too.

Well, I managed to get something working… but it isn’t pretty. What I wanted to do was to wrap a sub class around Cocos2dxHelper and just add a new init() method and override whatever other methods are required for the class to use Context and Activity, unfortunately between all the private and native method calls I couldn’t figure out how to make that approach work :pensive: As a last resort I have re-written Cocos2dxHelper.java so that it can use both Activity and Context for initialization as well as some code to prevent casting a Service Context to an Activity. I AM NOT a java developer and have only been using Cocos2dx for a few days so PLEASE let me know if I’m doing something really stupid here or if there’s a better way to do this!

Here’s the rewritten Cocos2dxHelper.java:

/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 ****************************************************************************/
package org.cocos2dx.lib;

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.LinkedHashSet;
import java.util.Set;
import java.lang.Runnable;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Build;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;


public class Cocos2dxHelper {
    // ===========================================================
    // Constants
    // ===========================================================
    private static final String PREFS_NAME = "Cocos2dxPrefsFile";
    private static final int RUNNABLES_PER_FRAME = 5;

    // ===========================================================
    // Fields
    // ===========================================================

    private static Cocos2dxMusic sCocos2dMusic;
    private static Cocos2dxSound sCocos2dSound;
    private static AssetManager sAssetManager;
    private static Cocos2dxAccelerometer sCocos2dxAccelerometer;
    private static boolean sAccelerometerEnabled;
    private static boolean sActivityVisible;
    private static String sPackageName;
    private static String sFileDirectory;
    private static Context sContext = null;
    private static Cocos2dxHelperListener sCocos2dxHelperListener;
    private static Set<OnActivityResultListener> onActivityResultListeners = new LinkedHashSet<OnActivityResultListener>();


    // ===========================================================
    // Constructors
    // ===========================================================

    public static void runOnGLThread(final Runnable r) {
        if(sContext instanceof Activity)
        {
            ((Cocos2dxActivity)sContext).runOnGLThread(r);
        }
    }

    private static boolean sInited = false;
    
    public static void init(final Activity activity) {
        if (!sInited) {
            final ApplicationInfo applicationInfo = activity.getApplicationInfo();
            
            Cocos2dxHelper.sCocos2dxHelperListener = (Cocos2dxHelperListener)activity;
                    
            Cocos2dxHelper.sPackageName = applicationInfo.packageName;
            Cocos2dxHelper.sFileDirectory = activity.getFilesDir().getAbsolutePath();
            Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir);
    
            Cocos2dxHelper.sCocos2dxAccelerometer = new Cocos2dxAccelerometer(activity);
            Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(activity);
            Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(activity);
            Cocos2dxHelper.sAssetManager = activity.getAssets();
            Cocos2dxHelper.nativeSetContext((Context)activity, Cocos2dxHelper.sAssetManager);
    
            Cocos2dxBitmap.setContext(activity);
            Cocos2dxETCLoader.setContext(activity);
            sContext = (Context)activity;

            sInited = true;
        }
    }
    
    public static void init(final Context pContext, final Cocos2dxHelperListener pCocos2dxHelperListener) {
        if (!sInited) {
            final ApplicationInfo applicationInfo = pContext.getApplicationInfo();
        
            Cocos2dxHelper.sCocos2dxHelperListener = pCocos2dxHelperListener;

            Cocos2dxHelper.sPackageName = applicationInfo.packageName;
            Cocos2dxHelper.sFileDirectory = pContext.getFilesDir().getAbsolutePath();
            Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir);

            Cocos2dxHelper.sCocos2dxAccelerometer = new Cocos2dxAccelerometer(pContext);
            Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(pContext);
            Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(pContext);
            Cocos2dxHelper.sAssetManager = pContext.getAssets();
            Cocos2dxHelper.nativeSetContext(pContext, Cocos2dxHelper.sAssetManager);
            
            Cocos2dxBitmap.setContext(pContext);
            Cocos2dxETCLoader.setContext(pContext);
            sContext = pContext;

            sInited = true;
        }
    }

    public static Activity getActivity() {
        if(sContext instanceof Activity)
        {
            return (Activity)sContext;
        }
        else
        {
            return null;
        }
    }
    
    public static void addOnActivityResultListener(OnActivityResultListener listener) {
        onActivityResultListeners.add(listener);
    }
    
    public static Set<OnActivityResultListener> getOnActivityResultListeners() {
        return onActivityResultListeners;
    }
    
    public static boolean isActivityVisible(){
        return sActivityVisible;
    }

    // ===========================================================
    // Getter & Setter
    // ===========================================================

    // ===========================================================
    // Methods for/from SuperClass/Interfaces
    // ===========================================================

    // ===========================================================
    // Methods
    // ===========================================================

    private static native void nativeSetApkPath(final String pApkPath);

    private static native void nativeSetEditTextDialogResult(final byte[] pBytes);

    private static native void nativeSetContext(final Context pContext, final AssetManager pAssetManager);

    public static String getCocos2dxPackageName() {
        return Cocos2dxHelper.sPackageName;
    }

    public static String getCocos2dxWritablePath() {
        return Cocos2dxHelper.sFileDirectory;
    }

    public static String getCurrentLanguage() {
        return Locale.getDefault().getLanguage();
    }
    
    public static String getDeviceModel(){
        return Build.MODEL;
    }

    public static AssetManager getAssetManager() {
        return Cocos2dxHelper.sAssetManager;
    }

    public static void enableAccelerometer() {
        Cocos2dxHelper.sAccelerometerEnabled = true;
        Cocos2dxHelper.sCocos2dxAccelerometer.enable();
    }


    public static void setAccelerometerInterval(float interval) {
        Cocos2dxHelper.sCocos2dxAccelerometer.setInterval(interval);
    }

    public static void disableAccelerometer() {
        Cocos2dxHelper.sAccelerometerEnabled = false;
        Cocos2dxHelper.sCocos2dxAccelerometer.disable();
    }

    public static void preloadBackgroundMusic(final String pPath) {
        Cocos2dxHelper.sCocos2dMusic.preloadBackgroundMusic(pPath);
    }

    public static void playBackgroundMusic(final String pPath, final boolean isLoop) {
        Cocos2dxHelper.sCocos2dMusic.playBackgroundMusic(pPath, isLoop);
    }

    public static void resumeBackgroundMusic() {
        Cocos2dxHelper.sCocos2dMusic.resumeBackgroundMusic();
    }

    public static void pauseBackgroundMusic() {
        Cocos2dxHelper.sCocos2dMusic.pauseBackgroundMusic();
    }

    public static void stopBackgroundMusic() {
        Cocos2dxHelper.sCocos2dMusic.stopBackgroundMusic();
    }

    public static void rewindBackgroundMusic() {
        Cocos2dxHelper.sCocos2dMusic.rewindBackgroundMusic();
    }

    public static boolean isBackgroundMusicPlaying() {
        return Cocos2dxHelper.sCocos2dMusic.isBackgroundMusicPlaying();
    }

    public static float getBackgroundMusicVolume() {
        return Cocos2dxHelper.sCocos2dMusic.getBackgroundVolume();
    }

    public static void setBackgroundMusicVolume(final float volume) {
        Cocos2dxHelper.sCocos2dMusic.setBackgroundVolume(volume);
    }

    public static void preloadEffect(final String path) {
        Cocos2dxHelper.sCocos2dSound.preloadEffect(path);
    }

    public static int playEffect(final String path, final boolean isLoop, final float pitch, final float pan, final float gain) {
        return Cocos2dxHelper.sCocos2dSound.playEffect(path, isLoop, pitch, pan, gain);
    }

    public static void resumeEffect(final int soundId) {
        Cocos2dxHelper.sCocos2dSound.resumeEffect(soundId);
    }

    public static void pauseEffect(final int soundId) {
        Cocos2dxHelper.sCocos2dSound.pauseEffect(soundId);
    }

    public static void stopEffect(final int soundId) {
        Cocos2dxHelper.sCocos2dSound.stopEffect(soundId);
    }

    public static float getEffectsVolume() {
        return Cocos2dxHelper.sCocos2dSound.getEffectsVolume();
    }

    public static void setEffectsVolume(final float volume) {
        Cocos2dxHelper.sCocos2dSound.setEffectsVolume(volume);
    }

    public static void unloadEffect(final String path) {
        Cocos2dxHelper.sCocos2dSound.unloadEffect(path);
    }

    public static void pauseAllEffects() {
        Cocos2dxHelper.sCocos2dSound.pauseAllEffects();
    }

    public static void resumeAllEffects() {
        Cocos2dxHelper.sCocos2dSound.resumeAllEffects();
    }

    public static void stopAllEffects() {
        Cocos2dxHelper.sCocos2dSound.stopAllEffects();
    }

    public static void end() {
        Cocos2dxHelper.sCocos2dMusic.end();
        Cocos2dxHelper.sCocos2dSound.end();
    }

    public static void onResume() {
        sActivityVisible = true;
        if (Cocos2dxHelper.sAccelerometerEnabled) {
            Cocos2dxHelper.sCocos2dxAccelerometer.enable();
        }
    }

    public static void onPause() {
        sActivityVisible = false;
        if (Cocos2dxHelper.sAccelerometerEnabled) {
            Cocos2dxHelper.sCocos2dxAccelerometer.disable();
        }
    }

    public static void onEnterBackground() {
        sCocos2dSound.onEnterBackground();
        sCocos2dMusic.onEnterBackground();
    }
    
    public static void onEnterForeground() {
        sCocos2dSound.onEnterForeground();
        sCocos2dMusic.onEnterForeground();
    }
    
    public static void terminateProcess() {
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    private static void showDialog(final String pTitle, final String pMessage) {
        Cocos2dxHelper.sCocos2dxHelperListener.showDialog(pTitle, pMessage);
    }

    private static void showEditTextDialog(final String pTitle, final String pMessage, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
        Cocos2dxHelper.sCocos2dxHelperListener.showEditTextDialog(pTitle, pMessage, pInputMode, pInputFlag, pReturnType, pMaxLength);
    }

    public static void setEditTextDialogResult(final String pResult) {
        try {
            final byte[] bytesUTF8 = pResult.getBytes("UTF8");

            Cocos2dxHelper.sCocos2dxHelperListener.runOnGLThread(new Runnable() {
                @Override
                public void run() {
                    Cocos2dxHelper.nativeSetEditTextDialogResult(bytesUTF8);
                }
            });
        } catch (UnsupportedEncodingException pUnsupportedEncodingException) {
            /* Nothing. */
        }
    }

    public static int getDPI()
    {
        if (sContext != null && sContext instanceof Activity)
        {
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager wm = ((Activity)sContext).getWindowManager();
            if (wm != null)
            {
                Display d = wm.getDefaultDisplay();
                if (d != null)
                {
                    d.getMetrics(metrics);
                    return (int)(metrics.density*160.0f);
                }
            }
        }
        return -1;
    }
    
    // ===========================================================
     // Functions for CCUserDefault
     // ===========================================================
    
    public static boolean getBoolForKey(String key, boolean defaultValue) {
        SharedPreferences settings = sContext.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
        return settings.getBoolean(key, defaultValue);
    }
    
    public static int getIntegerForKey(String key, int defaultValue) {
        SharedPreferences settings = sContext.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
        return settings.getInt(key, defaultValue);
    }
    
    public static float getFloatForKey(String key, float defaultValue) {
        SharedPreferences settings = sContext.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
        return settings.getFloat(key, defaultValue);
    }
    
    public static double getDoubleForKey(String key, double defaultValue) {
        // SharedPreferences doesn't support saving double value
        SharedPreferences settings = sContext.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
        return settings.getFloat(key, (float)defaultValue);
    }
    
    public static String getStringForKey(String key, String defaultValue) {
        SharedPreferences settings = sContext.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
        return settings.getString(key, defaultValue);
    }
    
    public static void setBoolForKey(String key, boolean value) {
        SharedPreferences settings = sContext.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }
    
    public static void setIntegerForKey(String key, int value) {
        SharedPreferences settings = sContext.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(key, value);
        editor.commit();
    }
    
    public static void setFloatForKey(String key, float value) {
        SharedPreferences settings = sContext.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putFloat(key, value);
        editor.commit();
    }
    
    public static void setDoubleForKey(String key, double value) {
        // SharedPreferences doesn't support recording double value
        SharedPreferences settings = sContext.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putFloat(key, (float)value);
        editor.commit();
    }
    
    public static void setStringForKey(String key, String value) {
        SharedPreferences settings = sContext.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        editor.commit();
    }
    
    // ===========================================================
    // Inner and Anonymous Classes
    // ===========================================================

    public static interface Cocos2dxHelperListener {
        public void showDialog(final String pTitle, final String pMessage);
        public void showEditTextDialog(final String pTitle, final String pMessage, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength);

        public void runOnGLThread(final Runnable pRunnable);
    }
}

Here’s a slightly modified version of the code from this post Android Live Wallpaper using Cocos2d-x which is based on the tutorial here http://www.learnopengles.com/how-to-use-opengl-es-2-in-an-android-live-wallpaper/.

AppWallpaperService.java:

/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.cpp;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.os.Build;
import android.os.Bundle;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.SurfaceHolder;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLSurfaceView;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;

import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import org.cocos2dx.lib.Cocos2dxHelper;
import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener;
import org.cocos2dx.lib.Cocos2dxRenderer;


public class AppWallpaperService extends WallpaperService
{
    /*static 
    {
        System.loadLibrary("cocos2dcpp");
    }*/
    
    @Override
    public Engine onCreateEngine()
    {
        // Updated from Cocos2dxAcivity loadLibrary from Manifest.xml
        try {
            ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            Bundle bundle = ai.metaData;
            try {
                String libName = bundle.getString("android.app.lib_name");
                System.loadLibrary(libName);
            } catch (Exception e) {
                 // ERROR
                e.printStackTrace();
            }
        } catch (PackageManager.NameNotFoundException e) {
             // ERROR
            e.printStackTrace();
        }
        
        return new GLEngine();
    }
    
    // Based on: http://www.learnopengles.com/how-to-use-opengl-es-2-in-an-android-live-wallpaper/
    protected class GLEngine extends Engine implements Cocos2dxHelper.Cocos2dxHelperListener
    {
        protected class WallpaperGLSurfaceView extends Cocos2dxGLSurfaceView
        {
            private static final String TAG = "WallpaperGLSurfaceView";

            WallpaperGLSurfaceView(Context context)
            {
                super(context);
            }

            @Override
            public SurfaceHolder getHolder()
            {
                return getSurfaceHolder();
            }

            public void onDestroy()
            {
                super.onDetachedFromWindow();
            }
        }

        // Based on: http://discuss.cocos2d-x.org/t/android-live-wallpaper-using-cocos2d-x/7757
        protected class Cocos2dxGLRenderer extends Cocos2dxRenderer
        {
            //prevent the cocos2dxRenderer from calling nativeInit
            @Override
            public void onSurfaceCreated(final GL10 pGL10, final EGLConfig pEGLConfig) {
            }
            
            @Override
            public void onSurfaceChanged(final GL10 pGL10, final int pWidth, final int pHeight) {
                setScreenWidthAndHeight(pWidth, pHeight);
                super.onSurfaceCreated(null, null);
            }

        }

        private static final String TAG = "GLEngine";

        private WallpaperGLSurfaceView mGLSurfaceView;
        private boolean rendererHasBeenSet;		

        @Override
        public void onCreate(SurfaceHolder surfaceHolder)
        {
            super.onCreate(surfaceHolder);

            //setTouchEventsEnabled(true);//Test StackOverflow ? 

            mGLSurfaceView = new WallpaperGLSurfaceView(AppWallpaperService.this);
            mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
            setRenderer(getNewRenderer());
            Cocos2dxHelper.init(AppWallpaperService.this, this);
        }

        @Override
        public void onVisibilityChanged(boolean visible)
        {
            super.onVisibilityChanged(visible);

            if (rendererHasBeenSet)
            {
                if (visible)
                {
                    Cocos2dxHelper.onResume();
                    mGLSurfaceView.onResume();
                }
                else
                {
                    Cocos2dxHelper.onPause();
                    mGLSurfaceView.onPause();														
                }
            }
        }		

        @Override
        public void onDestroy()
        {
            super.onDestroy();
            Cocos2dxHelper.end();
            mGLSurfaceView.onDestroy();
        }
        
        protected void setRenderer(Renderer renderer)
        {
            mGLSurfaceView.setCocos2dxRenderer((Cocos2dxRenderer) renderer);
            rendererHasBeenSet = true;
        }
    
        Renderer getNewRenderer()
        {
            Cocos2dxRenderer renderer = new Cocos2dxGLRenderer();
            return renderer;
        }
    
        protected void setPreserveEGLContextOnPause(boolean preserve)
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            {
                mGLSurfaceView.setPreserveEGLContextOnPause(preserve);
            }
        }		

        protected void setEGLContextClientVersion(int version)
        {
            mGLSurfaceView.setEGLContextClientVersion(version);
        }

        @Override
        public void showDialog(String pTitle, String pMessage) 
        {
        }

        @Override
        public void showEditTextDialog(String pTitle, String pMessage, int pInputMode, int pInputFlag, int pReturnType, int pMaxLength) 
        {
        }

        @Override
        public void runOnGLThread(Runnable pRunnable) 
        {
            mGLSurfaceView.queueEvent(pRunnable);
        }   
        
        @Override
        public void onTouchEvent(final MotionEvent pMotionEvent)
        {
            mGLSurfaceView.onTouchEvent(pMotionEvent);
        }
    }
}

And here’s a modified AndroidManifest.xml that defines both a main Activity and wallpaper Service entry point:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.cocos2dx.cpp"
    android:versionCode="11"
    android:versionName="1.0.8.1" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" >
    </uses-sdk>

    <!-- Tell the system this app requires OpenGL ES 2.0. -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" >
    </uses-feature>
    
    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        
        <!-- Tell Cocos2dxActivity the name of our .so -->
        <meta-data
            android:name="android.app.lib_name"
            android:value="cocos2dcpp" >
        </meta-data>

        <activity
            android:name="org.cocos2dx.cpp.AppActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:configChanges="orientation">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <service
            android:name="org.cocos2dx.cpp.AppWallpaperService"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_WALLPAPER" >
            
            <intent-filter>
                <action android:name="android.service.wallpaper.WallpaperService" />
            </intent-filter>

            <meta-data
                android:name="android.service.wallpaper"
                android:resource="@xml/mywallpaper" >
            </meta-data>
        </service>
        
    </application>

</manifest>

And here’s a screen capture of it running on my Galaxy S3:

If anyone has a better way to do this I’d love to hear, I really don’t want to maintain my own copy of Cocos2dxHelper.java separate from the main trunk :cry:

3 Likes

It’s just beautiful. And I always wanted to have my own.
By the way, I have no idea how to monetize it. Not sure that the sale of the application works fine now. Maybe iap? Not sure…

You managed to do it!
Congratulations!

I programmed in java, but I did not get the cocos engine so much detail, I will need some time to deal with the class Cocos2dxHelper.
I put it on my to-do list and I will let you know if I have something better.

Thanks, it works but I don’t know enough about the internals of Cocos to know if it will cause a problem somewhere else. I also don’t like re-writing code in the engine as it will be a pain to maintain if not included in the trunk. The best way would be to find a way to wrap the Cocos2dxHelper class but I couldn’t find a way to do it.

I’m only just getting started in app development but everything I’ve read makes it clear that advertising is the only way to make money unless you get lucky and make a “killer app” that everyone wants to actually buy. I personally intend to make every app available for free with embedded advertising AND without advertising for a low price. The problem with advertising in wallpaper apps is the only place to put the add is in the settings but most people don’t go to the settings page very often (even with lots of fancy settings). On the other hand the wallpaper app is the only app that’s visible all the time, its a shame there’s not a way to do advertising in the wallpaper without being annoying :frowning:

I think can also try to inherit from this class and override the necessary methods. I see it today, as soon as I get home.

Maybe prompt the user to unlock some content in exchange for viewing some advertising.

I considered the Cocos2dxHelper, so it is possible to extend it or make a wrapper around it. But since the sActivity is private, it is necessary to do a lot of wraps around the methods that use the sActivity.

Plus: Possible to make your own class without changing the original Cocos2dxHelper.

Minus: Many wrappers and a little duplicate of code -> If the interface of the original class will change, it will be necessary to modify own class.

If you’re interested, then I’ll do implementation tomorrow.

That sounds fine to me, I don’t mind maintaining a wrapper as long as it’s stable and not too extensive. I’m curious if you noticed the native method calls and if you have a solution for this?

private static native void nativeSetApkPath(final String pApkPath);

private static native void nativeSetEditTextDialogResult(final byte[] pBytes);

private static native void nativeSetContext(final Context pContext, final AssetManager pAssetManager);

This is what finally stopped my progress, they call native JNI cpp code that is in turn dependent on the package location and class name of Cocos2dHelper. I didn’t see a way to wrap or relocate any of this code because of the native code.

I inattentively looked the code last night((. And not considered that the Context can not be reduced to the Cocos2dxHelperListener.

I was planning to leave the native methods in place, since it private. And to add the sContext field and init() method with Context parameter. Stored Context in the sContext, and after verifying call the original init method in the custom init method.

Another way would be to override the init, but it not possible to call private methods from it.
By the way, native methods can be wrapped, but only if it is not private.

So I have to admit that I have no better solution.

But in this there is a plus - Your solution is the best to date :wink:

I’m posting an update that fixes an issue causing the wallpaper to crash during certain life cycle events. It appears that a service’s onVisibilityChanged() is fired with “visibility” on at times when the view is not interactive and therefore not drawable. This was causing the wallpaper to crash randomly during installation and during system boot before getting to the desktop. To fix this I now check PowerManager.isScreenOn() in onVisibilityChanged() before actually checking the desktop visibility. Here are the changes…

AppWallpaperService.java:

/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.cpp;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.SurfaceHolder;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLSurfaceView;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;

import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import org.cocos2dx.lib.Cocos2dxHelper;
import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener;
import org.cocos2dx.lib.Cocos2dxRenderer;


public class AppWallpaperService extends WallpaperService
{
    /*static
    {
        System.loadLibrary("cocos2dcpp");
    }*/
    
	@Override
	public Engine onCreateEngine()
	{
        // Updated from Cocos2dxAcivity loadLibrary from Manifest.xml
		try {
			ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
			Bundle bundle = ai.metaData;
			try {
        		String libName = bundle.getString("android.app.lib_name");
        		System.loadLibrary(libName);
			} catch (Exception e) {
		 		// ERROR
				e.printStackTrace();
			}
		} catch (PackageManager.NameNotFoundException e) {
		 	// ERROR
			e.printStackTrace();
		}
		
		return new GLEngine();
	}
	
    // Based on: http://www.learnopengles.com/how-to-use-opengl-es-2-in-an-android-live-wallpaper/
	protected class GLEngine extends Engine implements Cocos2dxHelper.Cocos2dxHelperListener
	{
		protected class WallpaperGLSurfaceView extends Cocos2dxGLSurfaceView
		{
			private static final String TAG = "WallpaperGLSurfaceView";

			WallpaperGLSurfaceView(Context context)
			{
				super(context);
			}

			@Override
			public SurfaceHolder getHolder()
			{
				return getSurfaceHolder();
			}

			public void onDestroy()
			{
				super.onDetachedFromWindow();
			}
		}

        // Based on: http://discuss.cocos2d-x.org/t/android-live-wallpaper-using-cocos2d-x/7757
        protected class Cocos2dxGLRenderer extends Cocos2dxRenderer
        {
        	//prevent the cocos2dxRenderer from calling nativeInit
			@Override
        	public void onSurfaceCreated(final GL10 pGL10, final EGLConfig pEGLConfig) {
        	}
			
        	@Override
        	public void onSurfaceChanged(final GL10 pGL10, final int pWidth, final int pHeight) {
    			setScreenWidthAndHeight(pWidth, pHeight);
                
    			super.onSurfaceCreated(null, null);
        	}
        }

		private static final String TAG = "GLEngine";

        private PowerManager powerManager;
		private WallpaperGLSurfaceView mGLSurfaceView;
		private boolean rendererHasBeenSet;

		@Override
		public void onCreate(SurfaceHolder surfaceHolder)
		{
			super.onCreate(surfaceHolder);

            //setTouchEventsEnabled(true);//Test StackOverflow ?
            
            powerManager = (PowerManager) getSystemService(POWER_SERVICE);

			mGLSurfaceView = new WallpaperGLSurfaceView(AppWallpaperService.this);
            mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
            setRenderer(getNewRenderer());
            Cocos2dxHelper.init(AppWallpaperService.this, this);
		}

		@Override
		public void onVisibilityChanged(boolean visible)
		{
			super.onVisibilityChanged(visible);
            
			if (rendererHasBeenSet && powerManager.isScreenOn())
			{
				if (visible)
				{
                    Cocos2dxHelper.onResume();
					mGLSurfaceView.onResume();
				}
				else
				{
                    Cocos2dxHelper.onPause();
					mGLSurfaceView.onPause();
				}
			}
		}

		@Override
		public void onDestroy()
		{
			super.onDestroy();
            
            Cocos2dxHelper.end();
			mGLSurfaceView.onDestroy();
		}
		
		protected void setRenderer(Renderer renderer)
		{
			mGLSurfaceView.setCocos2dxRenderer((Cocos2dxRenderer) renderer);
			rendererHasBeenSet = true;
		}
	
	    Renderer getNewRenderer()
	    {
			Cocos2dxRenderer renderer = new Cocos2dxGLRenderer();
			return renderer;
	    }
	
		protected void setPreserveEGLContextOnPause(boolean preserve)
		{
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
			{
				mGLSurfaceView.setPreserveEGLContextOnPause(preserve);
			}
		}

		protected void setEGLContextClientVersion(int version)
		{
			mGLSurfaceView.setEGLContextClientVersion(version);
		}

        @Override
        public void showDialog(String pTitle, String pMessage)
        {
        }

        @Override
        public void showEditTextDialog(String pTitle, String pMessage, int pInputMode, int pInputFlag, int pReturnType, int pMaxLength)
        {
        }

        @Override
        public void runOnGLThread(Runnable pRunnable)
        {
            mGLSurfaceView.queueEvent(pRunnable);
        }
        
        @Override
        public void onTouchEvent(final MotionEvent pMotionEvent)
        {
        	mGLSurfaceView.onTouchEvent(pMotionEvent);
        }
	}
}

Is any better solutions was found to add constructor from Context only?

Or maybe at least there is a way to upload Cocos2dxHelper.java file not from cocos folder? So I could use original file for common projects and special one (with my changes) in one ??