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 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