作者 潘达康

H5聚合调原生SDK,初步调试完成

*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
.externalNativeBuild
.cxx
# Built application files
*.apk
*.ap_
# Files for the Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# Intellij
*.iml
# Keystore files
*.jks
... ...
# Default ignored files
/shelf/
/workspace.xml
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="11" />
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="GRADLE" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="MavenRepo" />
<option name="name" value="MavenRepo" />
<option name="url" value="https://repo.maven.apache.org/maven2/" />
</remote-repository>
<remote-repository>
<option name="id" value="BintrayJCenter" />
<option name="name" value="BintrayJCenter" />
<option name="url" value="https://jcenter.bintray.com/" />
</remote-repository>
<remote-repository>
<option name="id" value="Google" />
<option name="name" value="Google" />
<option name="url" value="https://dl.google.com/dl/android/maven2/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="11" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
... ...
/build
\ No newline at end of file
... ...
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 29
buildToolsVersion "30.0.1"
aaptOptions.cruncherEnabled = false
aaptOptions.useNewCruncher = false
defaultConfig {
applicationId "com.stss.h5sdk.demo"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(include: ["*.jar", "*.aar"], dir: "libs")
}
\ No newline at end of file
... ...
不能预览此文件类型
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
\ No newline at end of file
... ...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.agg.h5game">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="com.agg.h5game.AggH5GameApplication"
android:allowBackup="true"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:supportsRtl="true"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:usesCleartextTraffic="true">
<activity
android:name="com.agg.h5game.AggH5SplashActivity"
android:configChanges="keyboardHidden|orientation|screenSize|screenLayout"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.agg.h5game.AggH5MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize|screenLayout"
android:screenOrientation="sensorLandscape" />
<meta-data
android:name="GAME_ID"
android:value="1" />
<meta-data
android:name="CLIENT_ID"
android:value="1" />
<meta-data
android:name="h5game"
android:value="https://cdn.7277.cn/unite/h5sdk/710/1/sdk.html" />
</application>
</manifest>
\ No newline at end of file
... ...
stss_channel=1
stss_gameId=1
stss_appKey=987654321
stss_ORIENTATION=landscape
stss_logcat = 1
\ No newline at end of file
... ...
package com.agg.h5game;
import android.webkit.JavascriptInterface;
import com.agg.h5game.tools.AggH5Log;
public class AggH5AndroidToJs extends Object {
@JavascriptInterface
public void roleCreate(String roleParams) {
AggH5Log.d("ZhenWan", "roleCreate " + roleParams);
}
@JavascriptInterface
public void roleEnterGame(String roleParams) {
AggH5Log.d("ZhenWan", "roleEnterGame " + roleParams);
}
@JavascriptInterface
public void roleUpgrade(String roleParams) {
AggH5Log.d("ZhenWan", "roleUpgrade " + roleParams);
}
@JavascriptInterface
public void logout() {
}
@JavascriptInterface
public void orderAndPay(String payParams) {
AggH5Log.d("ZhenWan", "orderAndPay " + payParams);
}
}
... ...
package com.agg.h5game;
import android.app.Application;
import com.agg.h5game.tools.AggH5Log;
import com.stss.sdk.STSSAggApplication;
public class AggH5GameApplication extends STSSAggApplication {
private static Application application;
public static Application getApplication() {
return application;
}
@Override
public void onCreate() {
super.onCreate();
AggH5Log.d("AggH5GameApplication", "app 启动");
application = this;
}
}
... ...
package com.agg.h5game;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.agg.h5game.tools.AggH5Log;
import com.agg.h5game.tools.AggH5Tools;
import com.agg.h5game.tools.ParamsTools;
import com.stss.sdk.InitResult;
import com.stss.sdk.PayResult;
import com.stss.sdk.STSSAggGame;
import com.stss.sdk.STSSAggSdkListener;
import com.stss.sdk.constant.STSSAggCode;
import com.stss.sdk.verify.STSSUToken;
public class AggH5MainActivity extends Activity {
private final String TAG = "STSSAgg";
private Activity mContext;
private WebView webView;
private String h5game = "https://m.baidu.com";
private Boolean isToLogin = false;
private STSSUToken currToken = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.status_bar_color));
}
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
initView();
initSDK();
String gameUrl = AggH5Tools.getMetaData(mContext, "h5game");
if (!TextUtils.isEmpty(gameUrl)) {
h5game = gameUrl;
}
String newH5Url = h5game + "?" + ParamsTools.getParams(mContext, currToken);
AggH5Log.d(TAG, newH5Url);
webView.loadUrl(newH5Url);
}
private void initView() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
webView = findViewById(R.id.webview);
webView.addJavascriptInterface(new AggH5AndroidToJs(), "AggH5Game");
//页面缩放,适应手机屏幕
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(false);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDefaultTextEncodingName("UTF-8");
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//加载页面时如果不加改代码,页面会跳转到系统自带浏览器显示。
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
AggH5Log.d(TAG, "url for load: " + url);
try {
if (url.endsWith("qnsdkyhxy2.html") || url.endsWith("qnsdkysxy2.html")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return false;
} else if (url.startsWith("http:") || url.startsWith("https:")) {
//view.loadUrl(url);
return true;
} else {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return false;
}
} catch (Exception e) {
return false;
}
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
AggH5Log.d(TAG, "url for finish: " + url);
login();
}
});
}
private void initSDK() {
STSSAggGame.setSDKListener(mSdkListener);
STSSAggGame.init(mContext);
STSSAggGame.onCreate();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
STSSAggGame.exit();
}
return false;
}
private STSSAggSdkListener mSdkListener = new STSSAggSdkListener() {
// 状态回调(一般只用于日志打印)
@Override
public void onResult(final int code, final String msg) {
super.onResult(code, msg);
AggH5Log.e(TAG, "onResult(); code=" + code + ", msg=" + msg);
switch (code) {
case STSSAggCode.CODE_INIT_SUCCESS:
AggH5Log.d(TAG, "onResult 初始化成功");
break;
case STSSAggCode.CODE_INIT_FAIL:
AggH5Log.d(TAG, "onResult 初始化失败");
break;
case STSSAggCode.CODE_LOGIN_FAIL:
AggH5Log.d(TAG, "onResult 登录失败");
break;
case STSSAggCode.CODE_LOGIN_SUCCESS:
AggH5Log.d(TAG, "onResult 登录成功");
break;
case STSSAggCode.CODE_LOGOUT_SUCCESS:
AggH5Log.d(TAG, "onResult 注销成功");
break;
case STSSAggCode.CODE_EXIT_SUCCESS:
AggH5Log.d(TAG, "onResult 退出成功");
break;
default:
break;
}
}
// 初始化回调
@Override
public void onInitResult(InitResult result) {
super.onInitResult(result);
AggH5Log.e(TAG, "onInitResult(); result.extension=" + result.getExtension());
if (result.isSDKExit()) {
AggH5Log.d(TAG, "onInitResult->有退出框显示");
}
login();
}
// 登录成功回调
@Override
public void onAuthResult(final STSSUToken authResult) {
super.onAuthResult(authResult);
final String msg = "UserID=" + authResult.getGame_uid() + ", Token=" + authResult.getToken();
AggH5Log.e(TAG, "onAuthResult(); " + msg);
AggH5MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (authResult.isSuc()) {
currToken = authResult;
runOnUiThread(new Runnable() {
@Override
public void run() {
String newH5Url = h5game + "?" + ParamsTools.getParams(mContext, currToken);
AggH5Log.d(TAG, newH5Url);
webView.loadUrl(newH5Url);
}
});
} else {
//showToast("获取Token失败");
}
}
});
}
// 支付回调
@Override
public void onPayResult(final PayResult result) {
super.onPayResult(result);
AggH5Log.e(TAG, "onPayResult(); result.productName=" + result.getProductName());
AggH5MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//showToast("支付成功,商品:" + result.getProductName());
}
});
}
// 注销回调
@Override
public void onLogout() {
super.onLogout();
currToken = null;
AggH5Log.e(TAG, "onLogout();");
AggH5MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//showToast("个人中心退出帐号成功");
AggH5Log.d(TAG, "实现游戏的切换或注销帐号的流程,比如回到登陆界面");
}
});
}
// 退出回调
@Override
public void onExitResult() {
super.onExitResult();
AggH5MainActivity.this.finish();
System.exit(0);
}
};
private void login() {
if (!isToLogin) {
isToLogin = true;
return;
}
if (currToken != null) {
return;
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
STSSAggGame.login();
}
});
}
}, 1000);
}
@JavascriptInterface
public void logout() {
STSSAggGame.logout();
}
@JavascriptInterface
public void exit() {
STSSAggGame.exit();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
STSSAggGame.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
public void onStart() {
STSSAggGame.onStart();
super.onStart();
}
public void onPause() {
STSSAggGame.onPause();
webView.onPause();
super.onPause();
}
public void onResume() {
STSSAggGame.onResume();
webView.onResume();
super.onResume();
}
public void onNewIntent(Intent newIntent) {
STSSAggGame.onNewIntent(newIntent);
super.onNewIntent(newIntent);
}
public void onStop() {
STSSAggGame.onStop();
super.onStop();
}
public void onDestroy() {
STSSAggGame.onDestroy();
super.onDestroy();
}
public void onRestart() {
STSSAggGame.onRestart();
super.onRestart();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
STSSAggGame.onConfigurationChanged(newConfig);
}
// 如果是unity开发的游戏,需要把onBackPressed和onKeyDown注释掉
public void onBackPressed() {
AggH5Log.d(TAG, "OnBackPressed.");
STSSAggGame.onBackPressed();
STSSAggGame.exit();
// super.onBackPressed();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
STSSAggGame.onRequestPermissionsResult(requestCode, permissions, grantResults);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
\ No newline at end of file
... ...
package com.agg.h5game;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
public class AggH5SplashActivity extends Activity {
private final static int TIME = 2000; //闪屏保持的时间(毫秒计)
@Override
protected void onCreate(Bundle savedInstanceState) {
// 隐藏标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 隐藏状态栏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
ImageView img_splash = findViewById(R.id.img_splash);
img_splash.setImageResource(R.drawable.splash);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(AggH5SplashActivity.this, AggH5MainActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
}
}, TIME);
}
}
\ No newline at end of file
... ...
package com.agg.h5game.tools;
import android.util.Log;
public class AggH5Log {
public static boolean enable = true;
public static int LOG_LEVEL = 4;
public static String TAG = "AggH5Game";
public static void setLogLevel(int level){
LOG_LEVEL = level;
}
public static void e(String tag, String log){
if (enable && LOG_LEVEL>=1) {
Log.e(TAG + "_" + tag, ""+log);
}
}
public static void w(String tag, String log){
if (enable && LOG_LEVEL>=2) {
Log.w(TAG + "_" + tag, ""+log);
}
}
public static void d(String tag, String log){
if (enable && LOG_LEVEL>=3) {
Log.d(TAG + "_" + tag, ""+log);
}
}
public static void i(String tag, String log){
if (enable && LOG_LEVEL>=4) {
Log.i(TAG + "_" + tag, ""+log);
}
}
}
... ...
package com.agg.h5game.tools;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class AggH5Tools {
// 获取Manifest.xml 中MetaData属性
public static String getMetaData(Context ctx, String key) {
try {
ApplicationInfo appInfo = ctx.getPackageManager()
.getApplicationInfo(ctx.getPackageName(),
PackageManager.GET_META_DATA);
if (appInfo != null && appInfo.metaData != null
&& appInfo.metaData.containsKey(key)) {
return "" + appInfo.metaData.get(key);
} else {
AggH5Log.e("TFSDK", "The meta-data key is not exists." + key);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/***
* 获取assets目录下文件内容
*
* @param context
* @param assetsFile
* @return
*/
public static String getAssetConfigs(Context context, String assetsFile) {
InputStreamReader reader = null;
BufferedReader br = null;
try {
reader = new InputStreamReader(context.getAssets().open(assetsFile));
br = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
reader = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static String getAssetsPropertiesContext(Context context, String fileName, String valueName) {
String value = "";
Properties properties = new Properties();
try {
properties.load(context.getAssets()
.open(fileName));
value = properties.getProperty(valueName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
/**
* 获取assets目录下面指定的.properties文件内容
*
* @param context
* @param assetsPropertiesFile
* @return
*/
public static Map<String, String> getAssetPropConfig(Context context,
String assetsPropertiesFile) {
try {
Properties pro = new Properties();
pro.load(context.getAssets().open(assetsPropertiesFile));
Map<String, String> result = new HashMap<String, String>();
for (Map.Entry<Object, Object> entry : pro.entrySet()) {
String keyStr = entry.getKey().toString().trim();
String keyVal = entry.getValue().toString().trim();
if (!result.containsKey(keyStr)) {
result.put(keyStr, keyVal);
}
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getLogicChannel(Context context, String prefix) {
ApplicationInfo appInfo = context.getApplicationInfo();
String sourceDir = appInfo.sourceDir;
String targetEntryName = findTargetEntryName(sourceDir, prefix);
if (!TextUtils.isEmpty(targetEntryName)) {
// 去掉 prefix_
String replaceStr = prefix + "_";
return targetEntryName.replace(replaceStr, "");
}
return "1";
}
private static String findTargetEntryName(String sourceDir, String prefix) {
String key = "META-INF/" + prefix;
try (ZipFile zip = new ZipFile(sourceDir)) {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.startsWith(key)) {
return entryName;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 是否第一次进入APP
*
* @param context
* @return
*/
public static boolean firstIn(Context context) {
SharedPreferences shared = context.getSharedPreferences("info", Context.MODE_PRIVATE);
boolean isfer = shared.getBoolean("isfer", true);
SharedPreferences.Editor editor = shared.edit();
if (isfer) {
//第一次进入
editor.putBoolean("isfer", false);
editor.commit();
return true;
} else {
//非第一次进入
return false;
}
}
/**
* 获取时间
*
* @return 返回时间,如20170829
*/
public static String getDay() {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());// 设置日期格式
Date now = new Date();
String day = df.format(now);// 获取当前的日期
return day;
}
/**
* 获取手机型号
*
* @return 手机型号
*/
public static String getSystemModel() {
return android.os.Build.MODEL;
}
public static Map<String, String> common2map(boolean is2h5) {
Map<String, String> datas = new HashMap<String, String>();
/*datas.put("game_id", ConfigInfor.gameId);
datas.put("client_id", ConfigInfor.clientId);
datas.put("dyClientId", ConfigInfor.dyClientId);
datas.put("imei", "0000-000000-0000000000000");
datas.put("oaid", ConfigInfor.oaid);
datas.put("device", AndroidTools.getDeviceInfor());
datas.put("os", "1");
datas.put("version", AndroidTools.getAndroidSDKVersion());
datas.put("sdkVersion", QNConstant.versionName);
datas.put("android_id", AndroidTools.getAndroidID(QNSdkManager.getInstance().getsApplication()));
if (switchWithKey("is_permissAuth").equals("Y")) {
//datas.put("imei", AndroidTools.getAndroidID(QNSdkManager.getInstance().getsApplication()));
datas.put("imei", AndroidTools.getImei(QNSdkManager.getInstance().getsApplication()));
} else {
datas.put("imei", AndroidTools.getAndroidID(QNSdkManager.getInstance().getsApplication()));
}
if (!is2h5 && QNSdkManager.getInstance().isLogin()) {
datas.put("uid", ConfigInfor.getInstance().getCurrentUserKey("uid"));
datas.put("username", ConfigInfor.getInstance().getCurrentUserKey("username"));
datas.put("token", ConfigInfor.getInstance().getCurrentUserKey("token"));
}
if (is2h5) {
datas.put("appKey", ConfigInfor.appKey);
datas.put("payJump", ConfigInfor.payJump);
datas.putAll(ConfigInfor.getInstance().swithConfigs);
}*/
return datas;
}
public static String map2string(Map<String, String> jsondatas) {
JSONObject json = new JSONObject();
for (String key : jsondatas.keySet()) {
String value = jsondatas.get(key);
if (value == null) {
continue;
}
if (value.contains("[") && value.contains("]")) {
try {
json.put(key, new JSONArray(value));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (value.contains("{") && value.contains("}")) {
try {
json.put(key, new JSONObject(value));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
json.put(key, jsondatas.get(key).toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return json.toString();
}
}
... ...
package com.agg.h5game.tools;
import android.content.Context;
import com.stss.sdk.verify.STSSUToken;
import java.util.HashMap;
import java.util.Map;
public class ParamsTools {
public static String getParams(Context context, STSSUToken token) {
HashMap<String, String> params = new HashMap<>();
params.put("isAppType", "Android");
params.put("cid", AggH5Tools.getLogicChannel(context, "sid"));
if (token != null) {
params.put("channel_uid", token.getChannel_uid());
params.put("game_uid", token.getGame_uid());
params.put("token", token.getToken());
params.put("extension", token.getExtension());
}
return mapToQueryString(params);
}
public static String mapToQueryString(HashMap<String, String> map) {
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : map.entrySet()) {
if (stringBuilder.length() > 0) {
stringBuilder.append("&");
}
stringBuilder.append(entry.getKey()).append("=").append(entry.getValue());
}
return stringBuilder.toString();
}
}
... ...
package com.agg.h5game.tools.http;
import android.app.Activity;
import android.os.AsyncTask;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class AggH5HttpUtils extends AsyncTask<String, Integer, AggH5ResResult> {
QNHttpCallBack qnHttpCallBack;
Activity activity;
AggH5ResResult beginGetRequest(String urlAddress, String parame) {
AggH5ResResult responeResult = new AggH5ResResult(-1);
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(urlAddress);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(30 * 1000);
httpURLConnection.setReadTimeout(30 * 1000);
httpURLConnection.setRequestMethod("GET");
InputStream is = httpURLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String response = "";
String readLine = null;
while ((readLine = br.readLine()) != null) {
response = response + readLine;
}
is.close();
br.close();
response = new String(response.getBytes(), "utf-8");
responeResult.setStatus(0);
responeResult.setResult(response);
} catch (IOException e) {
responeResult.setResult(e.getLocalizedMessage());
} finally {
if (httpURLConnection != null) {
// 释放资源
httpURLConnection.disconnect();
}
}
return responeResult;
}
AggH5ResResult beginPostRequest(String urlAddress, String parame) {
AggH5ResResult responeResult = new AggH5ResResult(-1);
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(urlAddress);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(30 * 1000);
httpURLConnection.setReadTimeout(30 * 1000);
httpURLConnection.setRequestMethod("POST");
DataOutputStream data = new DataOutputStream(httpURLConnection.getOutputStream());
data.writeBytes(parame);
InputStream is = httpURLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String response = "";
String readLine = null;
while ((readLine = br.readLine()) != null) {
response += readLine;
}
is.close();
br.close();
response = new String(response.getBytes(), "utf-8");
responeResult.setStatus(0);
responeResult.setResult(response);
} catch (IOException e) {
responeResult.setResult(e.getLocalizedMessage());
} finally {
if (httpURLConnection != null) {
// 释放资源
httpURLConnection.disconnect();
}
}
return responeResult;
}
String getParams(JSONObject clientData) {
if (clientData == null) {
return null;
}
String data = clientData.toString();
try {
data = URLEncoder.encode(clientData.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return data;
}
/**
* 把游戏发来的数据进行处理,拼接成与服务器交互进行get请求的字符串
*
* @param data 游戏传来的数据
* @return str 返回排序过的一个字符串
*/
public static String jsonToString(JSONObject data) {
JSONObject jsonObject = new JSONObject();
jsonObject = data;
Iterator<String> sIterator = jsonObject.keys();
Map<String, String> map = new TreeMap<String, String>(
new Comparator<String>() {
@Override
public int compare(String obj1, String obj2) {
return obj1.compareTo(obj2);
}
});
String str = "";
while (sIterator.hasNext()) {
// 获得key
String key = sIterator.next();
if (jsonObject.isNull(key)) {
continue;
}
// 根据key获得value, value也可以是JSONObject,JSONArray,使用对应的参数接收即可
map.put(key, jsonObject.optString(key));
}
Set<String> keySet = map.keySet();
Iterator<String> iter = keySet.iterator();
while (iter.hasNext()) {
String key = iter.next();
if (map.isEmpty()) {
continue;
}
String mapValue = map.get(key);
try {
str = str + key + "=" + URLEncoder.encode(mapValue, "UTF-8") + "&";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return str;
}
/**
* 请求
*/
public void connect(String urlAddress, String method, JSONObject parame,
Activity activity, QNHttpCallBack httpCallBack) {
if (method == "get") {
qnHttpCallBack = httpCallBack;
this.activity = activity;
// progressDialog = ProgressDialog.show(activity, null, null);
String client = getParams(parame);
if (urlAddress == null || urlAddress.length() == 0) {
return;
}
if (parame == null) {
this.execute(urlAddress, null, "get");
} else {
this.execute(urlAddress, client, "get");
}
} else if (method == "post") {
qnHttpCallBack = httpCallBack;
this.activity = activity;
// progressDialog = ProgressDialog.show(activity, null, null);
String client = AggH5HttpUtils.jsonToString(parame);
if (urlAddress == null || urlAddress.length() == 0) {
return;
}
if (parame == null) {
this.execute(urlAddress, null, "post");
} else {
this.execute(urlAddress, client, "post");
}
}
}
@Override
protected AggH5ResResult doInBackground(String... strings) {
if (strings[2] == "get") {
return beginGetRequest(strings[0], strings[1]);
} else if (strings[2] == "post") {
return beginPostRequest(strings[0], strings[1]);
}
return beginPostRequest(strings[0], strings[1]);
}
@Override
protected void onPostExecute(AggH5ResResult result) {
super.onPostExecute(result);
if (result.getStatus() == 0) {
JSONObject rObject = null;
try {
rObject = new JSONObject(result.getResult());
if (rObject.getInt("code") == 0) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "" + rObject.optString("msg"));
qnHttpCallBack.onFailure(jsonObject);
return;
}
if (qnHttpCallBack == null) {
return;
}
qnHttpCallBack.onSuccess(rObject);
} catch (JSONException e) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("catchMsg", result.getResult());
qnHttpCallBack.onFailure(jsonObject);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} else {
JSONObject json = new JSONObject();
try {
json.put("msg", "网络错误");
} catch (JSONException e) {
e.printStackTrace();
}
qnHttpCallBack.onFailure(json);
}
}
}
... ...
package com.agg.h5game.tools.http;
public class AggH5ResResult {
public AggH5ResResult(int status) {
super();
this.status = status;
}
/**
* 结果标志,0为合法结果 非0为非法结果
*/
int status;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
/**
* 0时,里面为合法结果 非0时,里面有网络请求结果
*/
String result;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
... ...
package com.agg.h5game.tools.http;
import org.json.JSONObject;
public interface QNHttpCallBack {
void onSuccess(JSONObject result);
void onFailure(JSONObject result);
}
... ...
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha = "0.0"
android:toAlpha = "1.0"
android:duration = "2000" />
</set>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha = "1.0"
android:toAlpha = "0.0"
android:duration = "2000" />
</set>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/img_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/splash" />
</LinearLayout>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="status_bar_color">#fff0da</color>
</resources>
\ No newline at end of file
... ...
<resources>
<string name="app_name">柒玩H5聚合</string>
</resources>
\ No newline at end of file
... ...
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
</resources>
\ No newline at end of file
... ...
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
\ No newline at end of file
... ...
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
\ No newline at end of file
... ...
不能预览此文件类型
#Tue Sep 14 17:17:01 CST 2021
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
... ...
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
... ...
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
... ...
rootProject.name = "AggH5Game"
include ':app'
... ...