wjtx_native/app/src/main/java/com/hnjc/wjtx/MainActivity.java
2020-11-19 17:49:37 +08:00

448 lines
17 KiB
Java
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.hnjc.wjtx;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import com.hnjc.wjtx.util.AssetsUtil;
import com.hnjc.wjtx.util.StorageUtil;
import com.hnjc.wjtx.util.StringUtil;
import com.hnjc.wjtx.vivo.VivoUnionHelper;
import com.vivo.unionsdk.open.OrderResultInfo;
import com.vivo.unionsdk.open.VivoAccountCallback;
import com.vivo.unionsdk.open.VivoConstants;
import com.vivo.unionsdk.open.VivoExitCallback;
import com.vivo.unionsdk.open.VivoPayCallback;
import com.vivo.unionsdk.open.VivoPayInfo;
import com.vivo.unionsdk.open.VivoRoleInfo;
import com.vivo.unionsdk.open.VivoUnionSDK;
import org.egret.egretnativeandroid.EgretNativeAndroid;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
private final String TAG = "MainActivity";
private EgretNativeAndroid nativeAndroid;
private ImageView launchScreenImageView = null;
private FrameLayout rootLayout = null;
private Vibrator vibrator;
//用户uid
private String mUid = "";
private String mAuthToken = "";
//游戏订单号
private String cpPayOrderNumber;
//订单金额
private String cpOrderAmount;
private String appId;
private final VivoAccountCallback mAcccountCallback = new VivoAccountCallback() {
@Override
public void onVivoAccountLogin(String userName, String uid, String authToken) {
// 1. 收到登录成功回调后调用服务端接口校验登录有效性。arg2返回值为authtoken。服务端接口详见文档。校验登录代码略。
mUid = uid;
mAuthToken = authToken;
sendUidToGame(mUid, mAuthToken);
//登录成功
VivoUnionHelper.queryMissOrderResult(uid);
}
@Override
public void onVivoAccountLogout(int i) {
nativeAndroid.callExternalInterface("loginOut", "");
}
@Override
public void onVivoAccountLoginCancel() {
nativeAndroid.callExternalInterface("loginCancel", "");
}
};
private VivoPayCallback mVivoPayCallback = new VivoPayCallback() {
// 客户端返回的支付结果不可靠,请再查询服务器,以服务器端最终的支付结果为准;
@Override
public void onVivoPayResult(int code, OrderResultInfo orderResultInfo) {
Log.i(TAG, "onVivoPayResult: " + orderResultInfo.getTransNo());
Log.i(TAG, "CpOrderNumber: " + cpPayOrderNumber + " i = " + code);
String errmsg = "";
JSONObject obj = new JSONObject();
if (code == VivoConstants.PAYMENT_RESULT_CODE_SUCCESS) {
Toast.makeText(MainActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
/**
* !!!! 一定要加,否则无法通过上架审核 !!!
* !!! 商品发放成功以后通知vivo侧 !!!!
* 这里取transNo不要取错了 注意!!!
*/
VivoUnionHelper.reportOrderComplete(orderResultInfo.getTransNo());
Log.i(TAG, "sendCompleteOrderNotification: " + orderResultInfo.getTransNo());
} else if (code == VivoConstants.PAYMENT_RESULT_CODE_CANCEL) {
Toast.makeText(MainActivity.this, "取消支付", Toast.LENGTH_SHORT).show();
} else if (code == VivoConstants.PAYMENT_RESULT_CODE_UNKNOWN) {
Toast.makeText(MainActivity.this, "未知状态,请查询订单", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
}
try {
obj.put("errcode", code);
obj.put("errmsg", errmsg);
nativeAndroid.callExternalInterface("payResult", obj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String preloadPath = AssetsUtil.getDiskFileDir(this, this.getString(R.string.preload_path));
String gameUrl = this.getString(R.string.game_url);
appId = this.getString(R.string.app_id);
nativeAndroid = new EgretNativeAndroid(this);
if (!nativeAndroid.checkGlEsVersion()) {
Toast.makeText(this, "This device does not support OpenGL ES 2.0.",
Toast.LENGTH_LONG).show();
return;
}
nativeAndroid.config.showFPS = false;
nativeAndroid.config.fpsLogTime = 30;
nativeAndroid.config.disableNativeRender = false;
nativeAndroid.config.clearCache = false;
nativeAndroid.config.loadingTimeout = 0;
nativeAndroid.config.immersiveMode = true;
nativeAndroid.config.useCutout = true;
nativeAndroid.config.preloadPath = preloadPath;
setExternalInterfaces();
if (!nativeAndroid.initialize(gameUrl)) {
Toast.makeText(this, "Initialize native failed.",
Toast.LENGTH_LONG).show();
return;
}
setContentView(nativeAndroid.getRootFrameLayout());
rootLayout = nativeAndroid.getRootFrameLayout();
showLoadingView();
vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
//注册登录回调
VivoUnionSDK.registerAccountCallback(this, mAcccountCallback);
/**
* 动态获取访问手机标识符权限
* 这个在游戏中移动要加不然获取不到imei
*/
if(Build.VERSION.SDK_INT >= 23){
int hasPermission = checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
if (hasPermission != PackageManager.PERMISSION_GRANTED) {
//没有权限,向用户请求权限
requestPermissions( new String[]{Manifest.permission.READ_PHONE_STATE}, 0);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//用户同意,执行操作
}else{
finish();
}
}
}
@Override
protected void onPause() {
super.onPause();
nativeAndroid.pause();
}
@Override
protected void onResume() {
super.onResume();
nativeAndroid.resume();
}
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
VivoUnionSDK.exit(this, new VivoExitCallback() {
@Override
public void onExitCancel() {
}
@Override
public void onExitConfirm() {
nativeAndroid.exitGame();
finish();
}
});
return true;
} else {
return super.onKeyDown(keyCode, keyEvent);
}
}
private void setExternalInterfaces() {
nativeAndroid.setExternalInterface("sendToNative", message -> {
Log.d(TAG, "Get message: " + message);
nativeAndroid.callExternalInterface("sendToJS", "Get message: " + message);
});
nativeAndroid.setExternalInterface("removeNativeLoading", message -> {
Log.d(TAG, "removeNativeLoading: " + message);
hideLoadingView();
});
nativeAndroid.setExternalInterface("setLocalStorage", message -> {
Log.d(TAG, "setLocalStorage: " + message);
try{
JSONObject jsonObject = new JSONObject(message);
String key = jsonObject.getString("key");
String val = jsonObject.getString("val");
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
StorageUtil.writeString(sharedPref, key, val);
}
catch (JSONException e) {
Log.e(TAG, " onState message failed to analyze");
}
});
nativeAndroid.setExternalInterface("getLocalStorage", message -> {
Log.d(TAG, "getLocalStorage: " + message);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String val = StorageUtil.readString(sharedPref, message);
nativeAndroid.callExternalInterface("getLocalStorage", val);
});
nativeAndroid.setExternalInterface("removeLocalStorage", message -> {
Log.d(TAG, "removeLocalStorage: " + message);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
StorageUtil.removeString(sharedPref, message);
});
/**
* 震动须添加权限
* <uses-permission android:name="android.permission.VIBRATE"/>
* @param type {int} 震动类型 0: 短震动, 1: 长震动
* */
nativeAndroid.setExternalInterface("vibrate", message -> {
Log.d(TAG, "vibrate: " + message);
message = StringUtil.isBlank(message) ? "0" : message;
int type = Integer.getInteger(message);
long time = type == 0 ? 15 : 500;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(time, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
vibrator.vibrate(time);
}
});
nativeAndroid.setExternalInterface("showToast", message -> {
Log.d(TAG, "showToast: " + message);
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
});
nativeAndroid.setExternalInterface("getUid", message -> {
loginVivoAccount();
});
nativeAndroid.setExternalInterface("@onState", message -> {
Log.e(TAG, "Get @onState: " + message);
try{
JSONObject jsonObject = new JSONObject(message);
String state = jsonObject.getString("state");
handleStateEvent(state);
}
catch (JSONException e) {
Log.e(TAG, " onState message failed to analyze");
}
});
nativeAndroid.setExternalInterface("@onError", message -> Log.e(TAG, "Get @onError: " + message));
// 支付
nativeAndroid.setExternalInterface("pay", message -> {
try {
JSONObject jsonObject = new JSONObject(message);
String cpOrderId = jsonObject.getString("orderId");
String productCode = jsonObject.getString("productCode");
int count = jsonObject.getInt("count");
String money = jsonObject.getString("money"); // 未传
String notifyUrl = jsonObject.getString("notifyUrl"); // 未传
String productName = jsonObject.getString("productName"); // 未传
String productDesc = jsonObject.getString("productDesc"); //未传
String sign = jsonObject.getString("sign"); // 未传
//TODO: 平台的支付
VivoPayInfo vivoPayInfo = new VivoPayInfo.Builder()
.setAppId(appId)
.setCpOrderNo(cpOrderId)
.setNotifyUrl(notifyUrl)
.setOrderAmount(money)
.setProductName(productName)
.setProductDesc(productDesc)
.setVivoSignature(sign)
.setExtUid(mUid)
.build();
VivoUnionHelper.payV2(this, vivoPayInfo, mVivoPayCallback);
} catch (JSONException e) {
e.printStackTrace();
} catch ( Exception e ) {
e.printStackTrace();
}
});
//let data = {
// isCreateRole: isNew,
// roleCreateTime: Date.now(),
// serverId: 区服ID
// serverName: 区服名称
// userRoleId: 角色ID
// userRoleName: 角色名称
// userRoleBalance: giant.Core.hero.coin,
// vipLevel: giant.Core.hero.vipLevel,
// userRoleLevel: 角色等级
// partyId: 0,
// partyName: giant.Core.hero.camp,
// gameRoleGender: giant.Core.hero.gender,
// gameRolePower: giant.Core.hero.power,
// };
nativeAndroid.setExternalInterface("reportRoleInfo", message -> {
Log.i(TAG, "Get reportRoleInfo: " + message);
try {
JSONObject jsonObject = new JSONObject(message);
String userRoleId = jsonObject.getString("userRoleId");
String userRoleLevel = jsonObject.getString("userRoleLevel");
String userRoleName = jsonObject.getString("userRoleName");
String serverId = jsonObject.getString("serverId");
String serverName = jsonObject.getString("serverName");
VivoUnionHelper.reportRoleInfo(new VivoRoleInfo(userRoleId, userRoleLevel, userRoleName, serverId, serverName));
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Error reportRoleInfo:" + e);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void showLoadingView() {
launchScreenImageView = new ImageView(this);
launchScreenImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.m_loading);
launchScreenImageView.setImageDrawable(drawable);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT);
rootLayout.addView(launchScreenImageView, params);
}
private void handleStateEvent(String state) {
switch (state) {
case "running":
// hideLoadingView();
return;
default:
Log.i(TAG, state);
}
}
private void hideLoadingView() {
rootLayout.removeView(launchScreenImageView);
Drawable drawable = launchScreenImageView.getDrawable();
launchScreenImageView.setImageDrawable(null);
drawable.setCallback(null);
launchScreenImageView = null;
}
/**
* 登录vivo帐号
*/
public void loginVivoAccount() {
if (!TextUtils.isEmpty(mUid)) {
sendUidToGame(mUid, mAuthToken);
return;
}
/**
* 接入掉单补单接口一定要掉单注册成功后再调用登录接口
*/
VivoUnionHelper.login(this);
}
/**
* 登录成功后,进行支付
*/
public void payAfterLogin() {
if (TextUtils.isEmpty(mUid)) {
Toast.makeText(this, "支付失败,请先登录", Toast.LENGTH_SHORT).show();
return;
}
// VivoPayInfo vivoPayInfo = VivoSign.createPayInfo(mUid, getOrderBean());
// VivoUnionHelper.payV2(this, vivoPayInfo, mVivoPayCallback);
}
/**
* //直接调起微信或支付宝支付
*
* @param code 1表示微信2表示支付宝
*/
public void payAfterLogin(int code) {
if (TextUtils.isEmpty(mUid)) {
Toast.makeText(this, "支付失败,请先登录", Toast.LENGTH_SHORT).show();
return;
}
// VivoPayInfo vivoPayInfo = VivoSign.createPayInfo(mUid, getOrderBean());
// VivoUnionHelper.payNowV2(this, vivoPayInfo, mVivoPayCallback, code);
}
/**
* 未登录时,进行支付
*/
public void payWithoutLogin() {
// VivoPayInfo vivoPayInfo = VivoSign.createPayInfo(mUid, getOrderBean());
// VivoUnionHelper.payV2(this, vivoPayInfo, mVivoPayCallback);
}
/**
* 未登录时,进行支付,直接调起微信或支付宝支付
*
* @param code 1表示微信2表示支付宝
*/
public void payWithoutLogin(int code) {
// VivoPayInfo vivoPayInfo = VivoSign.createPayInfo(mUid, getOrderBean());
// VivoUnionHelper.payNowV2(this, vivoPayInfo, mVivoPayCallback, code);
}
private void sendUidToGame(String uid, String token) {
JSONObject obj = new JSONObject();
try {
obj.put("openid", uid);
obj.put("token", token);
nativeAndroid.callExternalInterface("sendUidToJS", obj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}