cocos2d-x android加速度监听导致崩溃问题

来源:互联网 发布:超星尔雅网络考试答案 编辑:程序博客网 时间:2024/06/05 21:53

          因为需要用到手机摇一摇的功能,所以需要监听加速度变化,并把变化传到上层(LUA)。在CCLayer添加LUA回调函数,在didAccelerate里面调用CCScriptEngineManager,调用LUA注册函数。问题出现,在win32和IOS上运作正常,在android上回调一会就会崩溃,如果不回调LUA HANDLER则

没问题,应该是android的某些问题导致lua内存错误。

         解决方法:修改Cocos2dxAccelerometer.java里面的onSensorChanged函数,修改回调C++部分,

@Override
 public void onSensorChanged(final SensorEvent pSensorEvent) {
  if (pSensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
   return;
  }

  float x = pSensorEvent.values[0];
  float y = pSensorEvent.values[1];
  final float z = pSensorEvent.values[2];

  /*
   * Because the axes are not swapped when the device's screen orientation
   * changes. So we should swap it here. In tablets such as Motorola Xoom,
   * the default orientation is landscape, so should consider this.
   */
  final int orientation = this.mContext.getResources().getConfiguration().orientation;

  if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
   final float tmp = x;
   x = -y;
   y = tmp;
  } else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
   final float tmp = x;
   x = y;
   y = -tmp;
  }

  final float tx = x;
  final float ty = y;
  Cocos2dxActivity activity = (Cocos2dxActivity)Cocos2dxActivity.singleAcitivy;
  activity.runOnGLThread(new Runnable() {
            public void run() {
          Cocos2dxAccelerometer.onSensorChanged(tx, ty, z, pSensorEvent.timestamp);
            }
        });
  
  /*
  if(BuildConfig.DEBUG) {
   Log.d(TAG, "x = " + pSensorEvent.values[0] + " y = " + pSensorEvent.values[1] + " z = " + pSensorEvent.values[2]);
  }
  */
 }

是andoird多线程调用引起的问题,要传到C++的主线程。

原创粉丝点击