cocos creator android back 返回事件
原先 cocos2dx 里边可以用键盘事件监听返回
if('keyboard' in cc.sys.capabilities){
var backEner = cc.EventListener.create({
event:cc.EventListener.KEYBOARD,
target:this,
onKeyPressed:function () {
},
onKeyReleased :function (keyCode,event) {
if (keyCode === cc.KEY.back) {
if(cc.sys.isNative){
}
}
}
});
cc.eventManager.addListener(backEner, this);
}
在 cocos create 里边用该方法行不通
systemEvent.on(SystemEventType.KEY_DOWN, ()=>{
if(event.keyCode === macro.KEY.back && sys.isNative){
}
},this)
看了一下只能配合 android 原生一起实现
项目/native\engine\android\app\src\org\ 目录下 AppActivity 类加上 android 事件监听
通过 android 原生调用js代码
import android.view.KeyEvent;
import com.cocos.lib.CocosActivity;
import com.cocos.lib.CocosJavascriptJavaBridge;
import com.cocos.lib.CocosHelper;
import com.cocos.service.SDKWrapper;
public class AppActivity extends CocosActivity {
static AppActivity appActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appActivity = this;
}
....
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
CocosHelper.runOnGameThread(new Runnable() {
@Override
public void run() {
CocosJavascriptJavaBridge.evalString("window.backMan.back()");
}
});
}
SDKWrapper.shared().onPause();
return super.onKeyDown(keyCode, event);
}
}
ts 的某个组件
import { _decorator,Component} from 'cc';
@ccclass('Login')
export class Login extends Component {
....
}
class backMan {
private static _instance : backMan = null!
public static getInstance(){
if(this._instance === null){
this._instance = new backMan()
}
return this._instance
}
back(){
...
}
}
(window as any).backMan = backMan.getInstance()
|