AndroidHarness.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. package com.jme3.app;
  2. import android.app.Activity;
  3. import android.app.AlertDialog;
  4. import android.content.DialogInterface;
  5. import android.content.pm.ActivityInfo;
  6. import android.graphics.drawable.Drawable;
  7. import android.graphics.drawable.NinePatchDrawable;
  8. import android.opengl.GLSurfaceView;
  9. import android.os.Bundle;
  10. import android.view.*;
  11. import android.view.ViewGroup.LayoutParams;
  12. import android.widget.FrameLayout;
  13. import android.widget.ImageView;
  14. import android.widget.TextView;
  15. import com.jme3.audio.AudioRenderer;
  16. import com.jme3.audio.android.AndroidAudioRenderer;
  17. import com.jme3.input.TouchInput;
  18. import com.jme3.input.controls.TouchListener;
  19. import com.jme3.input.controls.TouchTrigger;
  20. import com.jme3.input.event.TouchEvent;
  21. import com.jme3.system.AppSettings;
  22. import com.jme3.system.SystemListener;
  23. import com.jme3.system.android.AndroidConfigChooser.ConfigType;
  24. import com.jme3.system.android.JmeAndroidSystem;
  25. import com.jme3.system.android.OGLESContext;
  26. import java.io.PrintWriter;
  27. import java.io.StringWriter;
  28. import java.util.logging.Level;
  29. import java.util.logging.Logger;
  30. /**
  31. * <code>AndroidHarness</code> wraps a jme application object and runs it on
  32. * Android
  33. *
  34. * @author Kirill
  35. * @author larynx
  36. */
  37. public class AndroidHarness extends Activity implements TouchListener, DialogInterface.OnClickListener, SystemListener {
  38. protected final static Logger logger = Logger.getLogger(AndroidHarness.class.getName());
  39. /**
  40. * The application class to start
  41. */
  42. protected String appClass = "jme3test.android.Test";
  43. /**
  44. * The jme3 application object
  45. */
  46. protected Application app = null;
  47. /**
  48. * ConfigType.FASTEST is RGB565, GLSurfaceView default ConfigType.BEST is
  49. * RGBA8888 or better if supported by the hardware
  50. */
  51. protected ConfigType eglConfigType = ConfigType.FASTEST;
  52. /**
  53. * If true all valid and not valid egl configs are logged
  54. */
  55. protected boolean eglConfigVerboseLogging = false;
  56. /**
  57. * If true MouseEvents are generated from TouchEvents
  58. */
  59. protected boolean mouseEventsEnabled = true;
  60. /**
  61. * Flip X axis
  62. */
  63. protected boolean mouseEventsInvertX = true;
  64. /**
  65. * Flip Y axis
  66. */
  67. protected boolean mouseEventsInvertY = true;
  68. /**
  69. * if true finish this activity when the jme app is stopped
  70. */
  71. protected boolean finishOnAppStop = true;
  72. /**
  73. * set to false if you don't want the harness to handle the exit hook
  74. */
  75. protected boolean handleExitHook = true;
  76. /**
  77. * Title of the exit dialog, default is "Do you want to exit?"
  78. */
  79. protected String exitDialogTitle = "Do you want to exit?";
  80. /**
  81. * Message of the exit dialog, default is "Use your home key to bring this
  82. * app into the background or exit to terminate it."
  83. */
  84. protected String exitDialogMessage = "Use your home key to bring this app into the background or exit to terminate it.";
  85. /**
  86. * Set the screen window mode. If screenFullSize is true, then the
  87. * notification bar and title bar are removed and the screen covers the
  88. * entire display.   If screenFullSize is false, then the notification bar
  89. * remains visible if screenShowTitle is true while screenFullScreen is
  90. * false, then the title bar is also displayed under the notification bar.
  91. */
  92. protected boolean screenFullScreen = true;
  93. /**
  94. * if screenShowTitle is true while screenFullScreen is false, then the
  95. * title bar is also displayed under the notification bar
  96. */
  97. protected boolean screenShowTitle = true;
  98. /**
  99. * Splash Screen picture Resource ID. If a Splash Screen is desired, set
  100. * splashPicID to the value of the Resource ID (i.e. R.drawable.picname). If
  101. * splashPicID = 0, then no splash screen will be displayed.
  102. */
  103. protected int splashPicID = 0;
  104. /**
  105. * Set the screen orientation, default is SENSOR
  106. * ActivityInfo.SCREEN_ORIENTATION_* constants package
  107. * android.content.pm.ActivityInfo
  108. *
  109. * SCREEN_ORIENTATION_UNSPECIFIED SCREEN_ORIENTATION_LANDSCAPE
  110. * SCREEN_ORIENTATION_PORTRAIT SCREEN_ORIENTATION_USER
  111. * SCREEN_ORIENTATION_BEHIND SCREEN_ORIENTATION_SENSOR (default)
  112. * SCREEN_ORIENTATION_NOSENSOR
  113. */
  114. protected int screenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
  115. protected OGLESContext ctx;
  116. protected GLSurfaceView view = null;
  117. protected boolean isGLThreadPaused = true;
  118. protected ImageView splashImageView = null;
  119. protected FrameLayout frameLayout = null;
  120. final private String ESCAPE_EVENT = "TouchEscape";
  121. private boolean firstDrawFrame = true;
  122. private boolean inConfigChange = false;
  123. private class DataObject {
  124. protected Application app = null;
  125. }
  126. @Override
  127. public Object onRetainNonConfigurationInstance() {
  128. logger.log(Level.INFO, "onRetainNonConfigurationInstance called");
  129. final DataObject data = new DataObject();
  130. data.app = this.app;
  131. inConfigChange = true;
  132. logger.log(Level.INFO, "app: {0}", app.hashCode());
  133. logger.log(Level.INFO, "ctx: {0}", ctx.hashCode());
  134. logger.log(Level.INFO, "view: {0}", view.hashCode());
  135. logger.log(Level.INFO, "isGLThreadPaused: {0}", isGLThreadPaused);
  136. logger.log(Level.INFO, "inConfigChange: {0}", inConfigChange);
  137. return data;
  138. }
  139. @Override
  140. public void onCreate(Bundle savedInstanceState) {
  141. super.onCreate(savedInstanceState);
  142. JmeAndroidSystem.setActivity(this);
  143. if (screenFullScreen) {
  144. requestWindowFeature(Window.FEATURE_NO_TITLE);
  145. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  146. WindowManager.LayoutParams.FLAG_FULLSCREEN);
  147. } else {
  148. if (!screenShowTitle) {
  149. requestWindowFeature(Window.FEATURE_NO_TITLE);
  150. }
  151. }
  152. setRequestedOrientation(screenOrientation);
  153. final DataObject data = (DataObject) getLastNonConfigurationInstance();
  154. if (data != null) {
  155. logger.log(Level.INFO, "onCreate: onRetainNonConfigurationInstance is not null");
  156. this.app = data.app;
  157. ctx = (OGLESContext) app.getContext();
  158. view = ctx.createView(eglConfigType, eglConfigVerboseLogging);
  159. ctx.setSystemListener(this);
  160. layoutDisplay();
  161. logger.log(Level.INFO, "app: {0}", app.hashCode());
  162. logger.log(Level.INFO, "ctx: {0}", ctx.hashCode());
  163. logger.log(Level.INFO, "view: {0}", view.hashCode());
  164. } else {
  165. logger.log(Level.INFO, "onCreate: onRetainNonConfigurationInstance is null");
  166. // Create Settings
  167. AppSettings settings = new AppSettings(true);
  168. settings.setEmulateMouse(mouseEventsEnabled);
  169. settings.setEmulateMouseFlipAxis(mouseEventsInvertX, mouseEventsInvertY);
  170. // Create application instance
  171. try {
  172. if (app == null) {
  173. @SuppressWarnings("unchecked")
  174. Class<? extends Application> clazz = (Class<? extends Application>) Class.forName(appClass);
  175. app = clazz.newInstance();
  176. }
  177. app.setSettings(settings);
  178. app.start();
  179. ctx = (OGLESContext) app.getContext();
  180. view = ctx.createView(eglConfigType, eglConfigVerboseLogging);
  181. // Set the screen reolution
  182. //TODO try to find a better way to get a hand on the resolution
  183. WindowManager wind = this.getWindowManager();
  184. Display disp = wind.getDefaultDisplay();
  185. logger.log(Level.WARNING, "Resolution from Window: {0}, {1}", new Object[]{disp.getWidth(), disp.getHeight()});
  186. ctx.getSettings().setResolution(disp.getWidth(), disp.getHeight());
  187. // AndroidHarness wraps the app as a SystemListener.
  188. ctx.setSystemListener(this);
  189. layoutDisplay();
  190. } catch (Exception ex) {
  191. handleError("Class " + appClass + " init failed", ex);
  192. setContentView(new TextView(this));
  193. }
  194. }
  195. }
  196. @Override
  197. protected void onRestart() {
  198. super.onRestart();
  199. if (app != null) {
  200. app.restart();
  201. }
  202. logger.info("onRestart");
  203. }
  204. @Override
  205. protected void onStart() {
  206. super.onStart();
  207. logger.info("onStart");
  208. }
  209. @Override
  210. protected void onResume() {
  211. super.onResume();
  212. if (view != null) {
  213. view.onResume();
  214. }
  215. if (app != null) {
  216. //resume the audio
  217. AudioRenderer result = app.getAudioRenderer();
  218. if (result != null) {
  219. if (result instanceof AndroidAudioRenderer) {
  220. AndroidAudioRenderer renderer = (AndroidAudioRenderer) result;
  221. renderer.resumeAll();
  222. }
  223. }
  224. }
  225. isGLThreadPaused = false;
  226. logger.info("onResume");
  227. }
  228. @Override
  229. protected void onPause() {
  230. super.onPause();
  231. if (view != null) {
  232. view.onPause();
  233. }
  234. if (app != null) {
  235. //pause the audio
  236. AudioRenderer result = app.getAudioRenderer();
  237. if (result != null) {
  238. logger.log(Level.INFO, "pause: {0}", result.getClass().getSimpleName());
  239. if (result instanceof AndroidAudioRenderer) {
  240. AndroidAudioRenderer renderer = (AndroidAudioRenderer) result;
  241. renderer.pauseAll();
  242. }
  243. }
  244. }
  245. isGLThreadPaused = true;
  246. logger.info("onPause");
  247. }
  248. @Override
  249. protected void onStop() {
  250. super.onStop();
  251. logger.info("onStop");
  252. }
  253. @Override
  254. protected void onDestroy() {
  255. final DataObject data = (DataObject) getLastNonConfigurationInstance();
  256. if (data != null || inConfigChange) {
  257. logger.info("onDestroy: found DataObject or inConfigChange");
  258. } else {
  259. if (app != null) {
  260. app.stop(!isGLThreadPaused);
  261. }
  262. }
  263. logger.info("onDestroy");
  264. super.onDestroy();
  265. }
  266. public Application getJmeApplication() {
  267. return app;
  268. }
  269. /**
  270. * Called when an error has occurred. By default, will show an error message
  271. * to the user and print the exception/error to the log.
  272. */
  273. @Override
  274. public void handleError(final String errorMsg, final Throwable t) {
  275. String stackTrace = "";
  276. String title = "Error";
  277. if (t != null) {
  278. // Convert exception to string
  279. StringWriter sw = new StringWriter(100);
  280. t.printStackTrace(new PrintWriter(sw));
  281. stackTrace = sw.toString();
  282. title = t.toString();
  283. }
  284. final String finalTitle = title;
  285. final String finalMsg = (errorMsg != null ? errorMsg : "Uncaught Exception")
  286. + "\n" + stackTrace;
  287. logger.log(Level.SEVERE, finalMsg);
  288. runOnUiThread(new Runnable() {
  289. @Override
  290. public void run() {
  291. AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon)
  292. .setTitle(finalTitle).setPositiveButton("Kill", AndroidHarness.this).setMessage(finalMsg).create();
  293. dialog.show();
  294. }
  295. });
  296. }
  297. /**
  298. * Called by the android alert dialog, terminate the activity and OpenGL
  299. * rendering
  300. *
  301. * @param dialog
  302. * @param whichButton
  303. */
  304. public void onClick(DialogInterface dialog, int whichButton) {
  305. if (whichButton != -2) {
  306. if (app != null) {
  307. app.stop(true);
  308. }
  309. app = null;
  310. this.finish();
  311. }
  312. }
  313. /**
  314. * Gets called by the InputManager on all touch/drag/scale events
  315. */
  316. @Override
  317. public void onTouch(String name, TouchEvent evt, float tpf) {
  318. if (name.equals(ESCAPE_EVENT)) {
  319. switch (evt.getType()) {
  320. case KEY_UP:
  321. runOnUiThread(new Runnable() {
  322. @Override
  323. public void run() {
  324. AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon)
  325. .setTitle(exitDialogTitle).setPositiveButton("Yes", AndroidHarness.this).setNegativeButton("No", AndroidHarness.this).setMessage(exitDialogMessage).create();
  326. dialog.show();
  327. }
  328. });
  329. break;
  330. default:
  331. break;
  332. }
  333. }
  334. }
  335. public void layoutDisplay() {
  336. logger.log(Level.INFO, "Splash Screen Picture Resource ID: {0}", splashPicID);
  337. if (splashPicID != 0) {
  338. FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
  339. LayoutParams.FILL_PARENT,
  340. LayoutParams.FILL_PARENT,
  341. Gravity.CENTER);
  342. frameLayout = new FrameLayout(this);
  343. splashImageView = new ImageView(this);
  344. Drawable drawable = this.getResources().getDrawable(splashPicID);
  345. if (drawable instanceof NinePatchDrawable) {
  346. splashImageView.setBackgroundDrawable(drawable);
  347. } else {
  348. splashImageView.setImageResource(splashPicID);
  349. }
  350. if (view.getParent() != null) {
  351. ((ViewGroup)view.getParent()).removeView(view);
  352. }
  353. frameLayout.addView(view);
  354. if (splashImageView.getParent() != null) {
  355. ((ViewGroup)splashImageView.getParent()).removeView(splashImageView);
  356. }
  357. frameLayout.addView(splashImageView, lp);
  358. setContentView(frameLayout);
  359. logger.log(Level.INFO, "Splash Screen Created");
  360. } else {
  361. logger.log(Level.INFO, "Splash Screen Skipped.");
  362. setContentView(view);
  363. }
  364. }
  365. public void removeSplashScreen() {
  366. logger.log(Level.INFO, "Splash Screen Picture Resource ID: {0}", splashPicID);
  367. if (splashPicID != 0) {
  368. if (frameLayout != null) {
  369. if (splashImageView != null) {
  370. this.runOnUiThread(new Runnable() {
  371. @Override
  372. public void run() {
  373. splashImageView.setVisibility(View.INVISIBLE);
  374. frameLayout.removeView(splashImageView);
  375. }
  376. });
  377. } else {
  378. logger.log(Level.INFO, "splashImageView is null");
  379. }
  380. } else {
  381. logger.log(Level.INFO, "frameLayout is null");
  382. }
  383. }
  384. }
  385. public void initialize() {
  386. app.initialize();
  387. if (handleExitHook) {
  388. app.getInputManager().addMapping(ESCAPE_EVENT, new TouchTrigger(TouchInput.KEYCODE_BACK));
  389. app.getInputManager().addListener(this, new String[]{ESCAPE_EVENT});
  390. }
  391. }
  392. public void reshape(int width, int height) {
  393. app.reshape(width, height);
  394. }
  395. public void update() {
  396. app.update();
  397. // call to remove the splash screen, if present.
  398. // call after app.update() to make sure no gap between
  399. // splash screen going away and app display being shown.
  400. if (firstDrawFrame) {
  401. removeSplashScreen();
  402. firstDrawFrame = false;
  403. }
  404. }
  405. public void requestClose(boolean esc) {
  406. app.requestClose(esc);
  407. }
  408. public void destroy() {
  409. if (app != null) {
  410. app.destroy();
  411. }
  412. if (finishOnAppStop) {
  413. finish();
  414. }
  415. }
  416. public void gainFocus() {
  417. if (app != null) {
  418. app.gainFocus();
  419. }
  420. }
  421. public void loseFocus() {
  422. if (app != null) {
  423. app.loseFocus();
  424. }
  425. }
  426. }