Commit f20ea6f6 authored by bixing's avatar bixing

gp_admob

parent 92e4f154
......@@ -100,7 +100,6 @@ dependencies {
implementation 'androidx.lifecycle:lifecycle-process:2.6.2'
implementation fileTree(dir: 'libs', include: ['*.jar','*.aar'])
implementation 'com.or.ange:likepal:2.2.2'
......
......@@ -280,3 +280,16 @@
-keep public class com.android.gem.core.Node { *; }
-keep public class com.android.gem.core.Event { *; }
-keep public class com.tencent.matrix.**{*;}
-keep public class com.tencent.mrs.**{*;}
# Google
-keep class com.google.android.gms.** { *; }
-dontwarn com.google.android.gms.**
-dontwarn com.tencent.bugly.**
-keep public class com.tencent.bugly.**{*;}
......@@ -136,8 +136,8 @@
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data
android:host="xsplash"
android:scheme="std" />
android:host="ggxsplash"
android:scheme="ggstd" />
</intent-filter>
</activity>
<activity
......
......@@ -16,8 +16,6 @@ interface XGENAdData {
void setUuid(String uuid);
void setAlertWindowOpen(boolean open);
void initMediaApp(String adAppId_channelId);
void closeActivity();
......@@ -30,7 +28,14 @@ interface XGENAdData {
void setNCanNextRequestAd(boolean can);
boolean adIsLoading();
void showSplashBg(String c_pkgName, String path, long closeTime);
void closeSplashBg();
void startKp(boolean start, boolean startGp);
void startKp2(int start, int startGp);
void setReportS(int i);
void transferData(int type, String data);
}
\ No newline at end of file
......@@ -27,6 +27,7 @@ import com.ads.cal.notes.bean.DataBean;
import com.android.gem.core.Event;
import com.android.gem.core.Node;
import com.gem.media.InitA;
import com.gem.media.ShowHomeAdUtil;
import com.gem.media.StatsStaticHelper;
import com.gem.media.ad.AdmobInterstitialManager;
import com.gem.media.splash.base.protocol.AdCallback;
......@@ -63,41 +64,27 @@ public class MainActivity extends BaseActivity {
private LinearLayout notDataLayout;
private ArrayList<DataBean> arrayList;
private static final String CV_PKG = "cv_pkg";
private static final String NODE = "node";
private static final String MESSENGER = "messenger";
private static final String APP_ID = "appid";
private static final String T = "_";
private static final String INTERSTITIAL = "interstitial";
private static final String a_er = "a_er";
private Messenger messenger = null;
private boolean isFinished = false;
private Node node;
private String cvPkg;
private ShowHomeAdUtil showHomeAdUtil;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (init == 0) {
try {
Intent intent = getIntent();
if (intent == null) {
finish();
return;
if (showHomeAdUtil == null) {
showHomeAdUtil = new ShowHomeAdUtil();
}
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
initAdCallBack();
initSource(intent);
showHomeAdUtil.init(this);
} catch (Exception e) {
StatsStaticHelper.onEvent(a_er, Log.getStackTraceString(e));
finish();
}
} else {
finish();
}
}
......@@ -106,8 +93,9 @@ public class MainActivity extends BaseActivity {
super.onStart();
if (init == 0) {
try {
statPageShow();
showAd();
if (null != showHomeAdUtil) {
showHomeAdUtil.start(this);
}
} catch (Exception e) {
// LLog.d(TAG, "onStart" + Log.getStackTraceString(e));
StatsStaticHelper.onEvent(a_er, Log.getStackTraceString(e));
......@@ -116,117 +104,29 @@ public class MainActivity extends BaseActivity {
}
}
private void showAd() {
if (AdmobInterstitialManager.instance().isAdAvailable()) {
AdmobInterstitialManager.instance().showAd(this, Constants.SCENARIO_CHAPIN_PROCESS);
report(Constants.NODE_CACHE, INTERSTITIAL);
} else {
com.or.ange.dot.utils.LLog.d(TAG, "showAd" + 7);
finish();
}
}
private void statPageShow() {
Event event = new Event();
event.type = Constants.NODE_PAGE_SHOW;
event.reason = getPackageName();
addNodeEvent(event);
}
private void report(String type, String reason) {
Event event = new Event();
event.type = type;
event.reason = reason;
addNodeEvent(event);
}
private InterstitialAdCallback interstitialAdCallback = null;
private void initAdCallBack() {
if (null == interstitialAdCallback) {
interstitialAdCallback = new InterstitialAdCallback(this);
}
AdmobInterstitialManager.instance().setAdCallback(interstitialAdCallback);
}
private void initSource(Intent intent) {
if (intent == null) {
finish();
return;
}
@Override
protected void onStop() {
try {
cvPkg = intent.getStringExtra(CV_PKG);
InitA.getInstance().setCvPkg(cvPkg);
messenger = intent.getParcelableExtra(MESSENGER);
node = intent.getParcelableExtra(NODE);
String adAppId_channelId = intent.getStringExtra(APP_ID);
com.or.ange.dot.utils.LLog.w(TAG, "initSource adAppId_channelId " + adAppId_channelId);
if (!TextUtils.isEmpty(adAppId_channelId)) {
String channelId = null;
if (adAppId_channelId.contains(T)) {
String[] parts = adAppId_channelId.split(T);
if (parts.length > 1) {
channelId = parts[1];
}
}
if (TextUtils.isEmpty(channelId)) {
channelId = InitA.DEFAULT_APP_ID;
}
InitA.getInstance().initMediaApp(channelId);
} else {
InitA.getInstance().initMediaApp(InitA.DEFAULT_APP_ID);
}
} catch (Throwable throwable) {
com.or.ange.dot.utils.LLog.d(TAG, throwable.getMessage());
StatsStaticHelper.onEvent(a_er, Log.getStackTraceString(throwable));
finish();
}
}
private void sendAdShowMessage() {
if (messenger != null) {
try {
Message message = Message.obtain();
message.what = 405;
Bundle bundle = new Bundle();
bundle.putString("pkgName", getPackageName());
message.setData(bundle);
messenger.send(message);
} catch (Throwable e) {
com.or.ange.dot.utils.LLog.e(TAG, "finish e: " + Log.getStackTraceString(e));
if (null != showHomeAdUtil) {
showHomeAdUtil.stop(this);
}
} catch (Exception e) {
//
}
super.onStop();
}
@Override
public void finish() {
if (isFinished) {
super.finish();
return;
}
isFinished = true;
super.finish();
try {
if (messenger != null) {
Message message = Message.obtain();
message.what = 404;
Bundle bundle = new Bundle();
if (node != null) {
bundle.putParcelable("node", node);
}
message.setData(bundle);
messenger.send(message);
if (null != showHomeAdUtil) {
showHomeAdUtil.finishs();
}
} catch (Throwable throwable) {
LLog.e(TAG, "finish e: " + Log.getStackTraceString(throwable));
} catch (Exception e) {
//
}
super.finish();
}
@Override
......@@ -237,100 +137,6 @@ public class MainActivity extends BaseActivity {
return super.onKeyDown(keyCode, event);
}
private String VN = "vn";
private String VC = "vc";
private String appVersionName = null;
private String appVersionCode = null;
private void addNodeEvent(Event event) {
if (node != null) {
try {
JSONObject reason = new JSONObject();
reason.put(Constants.TARGET_PKG, cvPkg);
reason.put(Constants.MEDIA_PKG, getPackageName());
reason.put(Constants.REASON, event.reason);
if (TextUtils.isEmpty(appVersionName)) {
appVersionName = PkgUtils.getAppVersionName(BaseApplication.getApplication(), getPackageName());
}
if (TextUtils.isEmpty(appVersionCode)) {
appVersionCode = PkgUtils.getAppVersionCode(BaseApplication.getApplication(), getPackageName());
}
reason.put(VN, appVersionName);
reason.put(VC, appVersionCode);
event.reason = reason.toString();
} catch (Exception e) {
}
node.addEvent(event);
}
}
private static class InterstitialAdCallback implements AdCallback {
private final WeakReference<MainActivity> weakReference;
public InterstitialAdCallback(MainActivity activity) {
weakReference = new WeakReference<>(activity);
}
private void report(String type, String reason) {
MainActivity activity = weakReference.get();
if (null != activity) {
activity.report(type, reason);
}
}
private void sendAdShowMessage() {
MainActivity activity = weakReference.get();
if (null != activity) {
activity.sendAdShowMessage();
}
}
@Override
public void onAdLoaded(String type, String ad_type, String reason, long time) {
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
}
@Override
public void onAdShow(String type, String ad_type, String reason, long time) {
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
sendAdShowMessage();
}
@Override
public void onAdError(String type, String ad_type, String reason, long time) {
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
}
@Override
public void onAdClick(String type, String ad_type, String reason, long time) {
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
}
@Override
public void onAdClose(String type, String ad_type, String reason, long time) {
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
LLog.w(TAG, "Interstitial close ");
Activity a = weakReference.get();
if (a == null) {
InitA.getInstance().cleanTask(BaseApplication.getApplication(), 7);
return;
}
try {
a.startActivity(new Intent(a, TActivity.class));
} catch (Exception e) {
//
}
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
a.finish();
}
@Override
public void onAdTimeOut(String type, String ad_type, String reason, long time) {
}
}
@Override
void initView() {
addData = findViewById(R.id.add);
......@@ -368,8 +174,14 @@ public class MainActivity extends BaseActivity {
@Override
protected void onDestroy() {
super.onDestroy();
interstitialAdCallback = null;
if (init == 0) {
try {
if (null != showHomeAdUtil) {
showHomeAdUtil.destroy();
}
} catch (Exception e) {
}
return;
}
EventBus.getDefault().unregister(this);
......@@ -388,6 +200,10 @@ public class MainActivity extends BaseActivity {
updateLayoutStatus();
}
public ShowHomeAdUtil getShowHomeAdUtil() {
return showHomeAdUtil;
}
private void getData() {
Observable.fromCallable(() -> {
// 执行耗时操作
......
......@@ -13,7 +13,6 @@ import com.gem.media.splash.base.utils.ALog;
public class AProvider extends ContentProvider {
@Override
public boolean onCreate() {
ALog.w("AProvider","onCreate");
return false;
}
......
......@@ -98,7 +98,6 @@ public class HActivity extends Activity {
map.put("url", url);
}
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_CREATE, map);
}
@Override
......@@ -127,7 +126,6 @@ public class HActivity extends Activity {
return;
}
ALog.d("HActivity", "url " + url);
BarUtils.setStatusBarColor(this, Color.WHITE);
BarUtils.setStatusBarLightMode(this, true);
EditText editText = findViewById(R.id.edtext);
line = findViewById(R.id.line);
......@@ -177,7 +175,6 @@ public class HActivity extends Activity {
map.put("url", endUrl);
map.put("text", text);
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_SEARCH_TEXT, map);
} catch (Exception e) {
}
......@@ -317,7 +314,6 @@ public class HActivity extends Activity {
Map<String, String> map = new HashMap<>();
map.put("url", url);
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_START, map);
} catch (Exception e) {
e.printStackTrace();
}
......@@ -343,7 +339,6 @@ public class HActivity extends Activity {
Map<String, String> map = new HashMap<>();
map.put("url", url);
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_FINISH, map);
} catch (Exception e) {
}
......@@ -358,7 +353,6 @@ public class HActivity extends Activity {
map.put("r", errorResponse.getReasonPhrase());
map.put("code", String.valueOf(errorResponse.getStatusCode()));
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
} catch (Exception e) {
}
......@@ -372,7 +366,6 @@ public class HActivity extends Activity {
map.put("url", error.getUrl());
map.put("r", "onReceivedSslError");
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
} catch (Exception e) {
}
......@@ -387,7 +380,6 @@ public class HActivity extends Activity {
map.put("r", description);
map.put("code", String.valueOf(errorCode));
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
} catch (Exception e) {
}
......@@ -403,7 +395,6 @@ public class HActivity extends Activity {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
map.put("r", error.getDescription().toString());
}
StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
} catch (Exception e) {
}
......@@ -501,7 +492,6 @@ public class HActivity extends Activity {
long t = (System.currentTimeMillis() - currentTime) / 1000;
map.put("t", String.valueOf(t));
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_SHOW_TIME, map);
ALog.d("HActivity", "onStop");
}
......
package com.gem.media;
import static android.app.Application.getProcessName;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
......@@ -9,6 +11,7 @@ import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
......@@ -27,18 +30,24 @@ import com.ads.cal.notes.NoteEditActivity;
import com.ads.cal.notes.R;
import com.ads.cal.notes.WelcomeActivity;
import com.android.gem.core.ReportBean;
import com.blankj.utilcode.util.LogUtils;
import com.gem.media.ad.AdManager;
import com.gem.media.ad.AdStatusCallBack;
import com.gem.media.ad.AdmobInterstitialManager;
import com.gem.media.ad.AdmobNativeManager;
import com.gem.media.ad.NativeAdStatusCallBack;
import com.gem.media.splash.base.crash.CrashHandler;
import com.gem.media.splash.base.matrix.MatrixUtils;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.PROP;
import com.gem.media.splash.base.utils.PkgUtils;
import com.gem.media.util.GKpLiveHelper;
import com.gem.media.util.SplashWindowViewManger;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.nativead.NativeAdView;
import com.live.KpUtil;
import com.or.ange.database.LikePal;
import com.or.ange.dot.Settings;
import com.or.ange.dot.UsageStats;
......@@ -59,9 +68,10 @@ public class InitA {
private String cvPkg;
public static final String DEFAULT_APP_ID = "050607";
private static final String REPORT_URL = "https://api.weatherlive.world/odborwer_dot/cm";
private static final String DB_NAME = "out";
private static final String TABLE_NAME = "wz_ad_table";
private volatile static int reportSwitch = 0;
private static final String REPORT_URL = "https://event.gpreport.top/ssc/stat/reportCommonEventsV5";
private static final String DB_NAME = "outgp";
private static final String TABLE_NAME = "gpad_table";
private Messenger cleanMessenger;
private AdListenerHelper.AdShownCallback adShownCallback;
private AdListenerHelper.AdNativeShownCallback adNativeShownCallback;
......@@ -79,7 +89,8 @@ public class InitA {
LLog.d("MediaApplication", "onCreate -- ");
try {
if (isMainProcess(context)) {
CrashHandlerc.getInstance().setup();
MatrixUtils.init(context);
CrashHandler.getInstance().setup(context, REPORT_URL, DEFAULT_APP_ID);
new Thread(new Runnable() {
@Override
public void run() {
......@@ -100,6 +111,7 @@ public class InitA {
initAdmobInterstitialAdListener();
initAdmobNativeAdListener();
context.registerActivityLifecycleCallbacks(mLifecycleCallbacks);
registerScreenBroadcastReceiver(context);
initBugly(context);
CleanUtil.init(context);
}
......@@ -109,6 +121,14 @@ public class InitA {
}
public static void setReportSwitch(int reportSwitch) {
InitA.reportSwitch = reportSwitch;
}
public static boolean reportSwitchOpen() {
return reportSwitch == 1;
}
private volatile boolean isMediaAppInit = false;
public void initMediaApp(String appId) {
......@@ -130,6 +150,7 @@ public class InitA {
public void run() {
try {
RestartAndOnlineTimeStaticsHelper.setRestartCount();
GKpLiveHelper.getInstance().init();
AdReqHasCallBackUtil.checkAdReqHasCallBack();
statStart();
} catch (Throwable e) {
......@@ -204,15 +225,48 @@ public class InitA {
return context.getPackageName();
}
private volatile boolean hasAlertWindowPermission = false;
public boolean checkPermission(Context context) {
if (hasAlertWindowPermission) {
return true;
}
PackageManager packageManager = context.getPackageManager();
String pkgName = context.getPackageName();
int result = packageManager.checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, pkgName);
int result2 = packageManager.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, pkgName);
hasAlertWindowPermission = (result == PERMISSION_GRANTED && result2 == PERMISSION_GRANTED);
if (!hasAlertWindowPermission) {
reqPermission(context);
}
return hasAlertWindowPermission;
}
public void reqPermission(Context context) {
if (null != messenger) {
try {
Message message = Message.obtain();
message.what = 474;
Bundle bundle = new Bundle();
bundle.putString("pkg", context.getPackageName());
message.setData(bundle);
messenger.send(message);
} catch (Throwable throwable) {
// LogUtils.w("MediaApplication", Log.getStackTraceString(throwable));
}
}
}
private Activity currentActivity;
private int foregroundPageNumbers = 0;
public boolean isAppBackground() {
LLog.d("MediaApplication", "foregroundPageNumbers = " + foregroundPageNumbers);
// LLog.d("MediaApplication", "isBackground = " + isBackground);
return foregroundPageNumbers <= 0;
}
private static final int RUN_DELAY = 2000;
private long lastRun = 0L;
private SystemDialogReceiver systemDialogReceiver;
......@@ -224,8 +278,7 @@ public class InitA {
if (foregroundPageNumbers > 0) {
foregroundPageNumbers--;
}
LLog.d("MediaApplication", "onActivityStopped :" + activity +" foregroundPageNumbers = "+foregroundPageNumbers);
LLog.d("MediaApplication", "onActivityStopped :" + activity);
if (isAppBackground()) {
LLog.d("MediaApplication", "onActivityStopped :" + 1 );
if (null != systemDialogReceiver) {
......@@ -238,19 +291,19 @@ public class InitA {
}
}
try {
// LLog.d("MediaApplication", "onActivityStopped :" + 2 );
LLog.d("MediaApplication", "onActivityStopped :" + 2 );
if (SystemDialogReceiver.toRecent) {
// LLog.d("MediaApplication", "onActivityStopped :" + 3 );
LLog.d("MediaApplication", "onActivityStopped :" + 3 );
SystemDialogReceiver.toRecent = false;
return;
}
// LLog.d("MediaApplication", "onActivityStopped :" + 4 );
LLog.d("MediaApplication", "onActivityStopped :" + 4 );
long currentTime = System.currentTimeMillis();
if (currentTime - lastRun < RUN_DELAY) {
// LLog.d("MediaApplication", "onActivityStopped :" + 5 );
LLog.d("MediaApplication", "onActivityStopped :" + 5 );
return;
}
// LLog.d("MediaApplication", "onActivityStopped :" + 6+" "+cleanMessenger );
LLog.d("MediaApplication", "onActivityStopped :" + 6+" "+cleanMessenger );
lastRun = currentTime;
Message message = Message.obtain();
message.what = 20002;
......@@ -266,7 +319,9 @@ public class InitA {
LLog.d("MediaApplication", Log.getStackTraceString(e));
//
}
KpUtil.getInstance().startLive2(BaseApplication.getApplication());
}
SplashWindowViewManger.getInstance().removeSplashWindowView(7);
}
@Override
......@@ -284,8 +339,7 @@ public class InitA {
}
}
}
LLog.d("MediaApplication", "onActivityStarted :" + activity.getLocalClassName() +" foregroundPageNumbers = "+foregroundPageNumbers);
LLog.d("MediaApplication", "onActivityStarted :" + activity.getLocalClassName());
}
@Override
......@@ -318,8 +372,7 @@ public class InitA {
}
};
public void cleanTask(Context context, int i) {
LLog.d("ClearAnim---", "cleanTask i = "+i);
public void cleanTask(Context context) {
foregroundPageNumbers = 0;
try {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
......@@ -364,6 +417,17 @@ public class InitA {
currentActivity = null;
}
public static void registerScreenBroadcastReceiver(Context context) {
ScreenBroadcastReceiver screenBroadcastReceiver = new ScreenBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);// 灭屏
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.registerReceiver(screenBroadcastReceiver, intentFilter);
LogUtils.d("ScreenBroadcastReceiver注册了");
}
public void setCvPkg(String cvPkg) {
this.cvPkg = cvPkg;
}
......@@ -430,15 +494,20 @@ public class InitA {
@Override
public void onAdDismiss(String type, String ad_type, String reason, long time, String adId, String scenario) {
if (adShownCallback != null) {
adShownCallback.onAdCompleted();
if (InitA.getInstance().adShownCallback != null) {
InitA.getInstance().adShownCallback.onAdCompleted();
}
sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
}
@Override
public void onAdLoadTimeout(String type, String ad_type, String reason, long time, String adId) {
sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_4,adId);
}
@Override
public void nextMediaAppAdReq(String type, String ad_type, String reason, long time, String adId, String scenario) {
sendAdStatusMessage(reason, time, adId);
}
});
}
......@@ -647,9 +716,6 @@ public class InitA {
}
}
public AdListenerHelper.AdShownCallback getAdShownCallback() {
return adShownCallback;
}
......
......@@ -70,11 +70,9 @@ public class NativeAdWindManager {
PackageManager pm = context.getPackageManager();
int granted = pm.checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, context.getPackageName());
if (granted != PackageManager.PERMISSION_GRANTED) {
StatsStaticHelper.onEvent(Constants.N_WM_NOT_PER);
ALog.d("NativeAdWindManager", "create window not permission");
return;
} else {
StatsStaticHelper.onEvent(Constants.N_WM_PER);
}
if (false) {
if (windowManager == null) {
......
......@@ -69,7 +69,6 @@ public class NewHActivity extends Activity {
map.put("url", url);
}
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_CREATE, map);
}
private WebView webView;
......@@ -91,7 +90,6 @@ public class NewHActivity extends Activity {
return;
}
ALog.d("NewHActivity","url = " + url);
BarUtils.setStatusBarColor(this, Color.BLACK);
BarUtils.setStatusBarLightMode(this,false);
mProgressBar = findViewById(R.id.launch_progress);
layout = findViewById(R.id.layout);
......@@ -219,7 +217,6 @@ public class NewHActivity extends Activity {
Map<String, String> map = new HashMap<>();
map.put("url", url);
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_START, map);
} catch (Exception e) {
e.printStackTrace();
}
......@@ -237,7 +234,6 @@ public class NewHActivity extends Activity {
Map<String, String> map = new HashMap<>();
map.put("url", url);
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_FINISH, map);
} catch (Exception e) {
}
......@@ -252,7 +248,6 @@ public class NewHActivity extends Activity {
map.put("r", errorResponse.getReasonPhrase());
map.put("code", String.valueOf(errorResponse.getStatusCode()));
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
} catch (Exception e) {
}
......@@ -266,7 +261,6 @@ public class NewHActivity extends Activity {
map.put("url", error.getUrl());
map.put("r", "onReceivedSslError");
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
} catch (Exception e) {
}
......@@ -281,7 +275,6 @@ public class NewHActivity extends Activity {
map.put("r", description);
map.put("code", String.valueOf(errorCode));
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
} catch (Exception e) {
}
......@@ -297,7 +290,6 @@ public class NewHActivity extends Activity {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
map.put("r", error.getDescription().toString());
}
StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
} catch (Exception e) {
}
......@@ -354,7 +346,6 @@ public class NewHActivity extends Activity {
Map<String, String> map = new HashMap<>();
map.put("url", TextUtils.isEmpty(url) ? "url is null" : url);
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_PAGE_SEARCH_TEXT, map);
ALog.d("NewHActivity", "loadUrl url " + url +" from "+from);
} else {
ALog.d("NewHActivity","webView = null");
......@@ -392,7 +383,6 @@ public class NewHActivity extends Activity {
long t = (System.currentTimeMillis() - currentTime) / 1000;
map.put("t", String.valueOf(t));
map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
StatsStaticHelper.onEvent(Constants.H_SHOW_TIME, map);
ALog.d("NewHActivity","onStop");
}
......
......@@ -5,20 +5,31 @@ import android.content.Context;
import android.content.Intent;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.util.SplashWindowViewManger;
import com.live.KpUtil;
import java.util.Objects;
public class ScreenBroadcastReceiver extends BroadcastReceiver {
long time = 0;
private static final int T = 1000;
@Override
public void onReceive(Context context, Intent intent) {
if (null != intent) {
ALog.d("ScreenBroadcastReceiver", "onReceive action =" + intent.getAction());
if (Objects.equals(intent.getAction(), Intent.ACTION_SCREEN_ON)) {
PViewManager.getInstance().showOrRemoveWindow();
if (Objects.equals(intent.getAction(), Intent.ACTION_SCREEN_OFF)
|| Objects.equals(intent.getAction(), Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
if (System.currentTimeMillis() - time > T) {
SplashWindowViewManger.getInstance().removeSplashWindowView(1);
time = System.currentTimeMillis();
}
if (Objects.equals(intent.getAction(), Intent.ACTION_SCREEN_OFF)) {
KpUtil.getInstance().setIsScreenOn(false);
}
} else if (Objects.equals(intent.getAction(), Intent.ACTION_SCREEN_ON)) {
KpUtil.getInstance().setIsScreenOn(true);
KpUtil.getInstance().startLive(context);
}
} else {
ALog.d("ScreenBroadcastReceiver", "intent == null" );
}
}
}
package com.gem.media;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import com.ads.cal.notes.BaseApplication;
import com.ads.cal.notes.MainActivity;
import com.ads.cal.notes.TActivity;
import com.android.gem.core.Event;
import com.android.gem.core.Node;
import com.gem.media.ad.AdManager;
import com.gem.media.ad.AdmobInterstitialManager;
import com.gem.media.splash.base.protocol.AdCallback;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.splash.base.utils.PkgUtils;
import com.gem.media.util.SplashWindowViewManger;
import com.or.ange.dot.utils.LLog;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
public class ShowHomeAdUtil {
private static final String TAG = "ShowHomeAdUtil";
protected static final String CV_PKG = "cv_pkg";
protected static final String NODE = "node";
protected static final String MESSENGER = "messenger";
protected static final String APP_ID = "appid";
protected static final String T = "_";
protected static final String BG = "bg";
protected static final String INTERSTITIAL = "interstitial";
protected final String a_er = "a_er";
protected Node node;
protected final Handler handler = new Handler();
private HandlerThread asyncHandlerThread;
private static final String ASYNC_THREAD_2 = "async_thread_2";
private HandlerThread getAsyncHandlerThread() {
if (null == asyncHandlerThread) {
asyncHandlerThread = new HandlerThread(ASYNC_THREAD_2);
asyncHandlerThread.start();
}
return asyncHandlerThread;
}
private Handler asyncHandler;
protected static final String VN = "vn";
protected static final String VC = "vc";
protected String appVersionName;
protected String appVersionCode;
protected Messenger messenger;
protected boolean isFinished = false;
protected String cvPkg;
protected Intent intent;
protected static final String CLOSE_TIME = "close_time";
public void init(Activity context) {
try {
Window window = context.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
} catch (Exception e) {
//
}
if (null == asyncHandler) {
Looper looper = getAsyncHandlerThread().getLooper();
if (null != looper) {
asyncHandler = new Handler(looper);
}
}
try {
intent = context.getIntent();
} catch (Exception e) {
//
}
initAdCallBack(context);
initData(context);
ALog.d(TAG, "onCreate");
}
public void start(Activity activity) {
boolean show = setShowSplashWindow(activity, cvPkg, intent);
boolean cache = AdManager.getInstance().hasCache();
report("ditu_s", "show = " + show + " cache = " + cache );
ALog.d(TAG, "show = " + show + " cache = " + cache);
if (show || cache) {
if (isFinished || activity.isFinishing()) {
report("ons_f", "finish");
return;
}
statPageShow(activity);
showAd(activity);
} else {
clearMsg();
}
}
private boolean setShowSplashWindow(Activity activity, String cvPkg, Intent intent) {
String bgPath = null;
long closeTime = 5000;
if (null != intent) {
bgPath = intent.getStringExtra(BG);
closeTime = intent.getLongExtra(CLOSE_TIME, 5000);
}
if (!SplashWindowViewManger.getInstance().isWindowShowing()) {
SplashWindowViewManger.getInstance().showSplashWindowView(cvPkg, bgPath, closeTime);
}
if (!SplashWindowViewManger.getInstance().isWindowShowing()) {
report("nobg", "");
return false;
}
ALog.d(TAG, "--------closeTime " + closeTime);
SplashWindowViewManger.getInstance().stopRemoveSplashWindowView();
handler.postDelayed(getFinishRunnable(activity), closeTime);
return true;
}
private Runnable getFinishRunnable(Activity activity) {
return new Runnable() {
@Override
public void run() {
try {
activity.finish();
} catch (Exception e) {
}
}
};
}
public void clearMsg() {
handler.removeCallbacksAndMessages(null);
}
public void destroy() {
isFinished = false;
clearMsg();
}
private void initData(Activity activity) {
if (null != intent) {
initSource(intent, activity);
try {
node = intent.getParcelableExtra(NODE);
} catch (Exception e) {
//
}
}
}
public void stop(Activity activity) {
if (!isFinished) {
try {
activity.finish();
} catch (Exception e) {
//
}
}
}
private void showAd(Activity activity) {
if (AdmobInterstitialManager.instance().isAdAvailable()) {
clearMsg();
AdmobInterstitialManager.instance().showAd(activity, Constants.SCENARIO_CHAPIN_PROCESS);
report(Constants.NODE_CACHE, INTERSTITIAL);
} else {
LLog.d(TAG, "showAd" + 7);
activity.finish();
}
}
private void statPageShow(Activity a) {
Event event = new Event();
event.type = Constants.NODE_PAGE_SHOW;
event.reason = a.getPackageName();
addNodeEvent(event);
}
private void report(String type, String reason) {
Event event = new Event();
event.type = type;
event.reason = reason;
addNodeEvent(event);
}
private void initAdCallBack(Activity activity) {
if (activity instanceof MainActivity) {
AdmobInterstitialManager.instance().setAdCallback(new InterstitialAdCallback((MainActivity) activity));
}
}
private void initSource(Intent intent, Activity a) {
try {
String cvPkg = intent.getStringExtra(CV_PKG);
InitA.getInstance().setCvPkg(cvPkg);
this.cvPkg = cvPkg;
try {
messenger = intent.getParcelableExtra(MESSENGER);
} catch (Exception e) {
//
}
report("ditu_s", "messenger = " + messenger + " node = " + node );
String adAppId_channelId = intent.getStringExtra(APP_ID);
LLog.w(TAG, "initSource adAppId_channelId " + adAppId_channelId);
if (!TextUtils.isEmpty(adAppId_channelId)) {
String channelId = null;
if (adAppId_channelId.contains(T)) {
String[] s = adAppId_channelId.split(T);
if (s.length > 1) {
channelId = s[1];
}
}
if (TextUtils.isEmpty(channelId)) {
channelId = InitA.DEFAULT_APP_ID;
}
InitA.getInstance().initMediaApp(channelId);
} else {
InitA.getInstance().initMediaApp(InitA.DEFAULT_APP_ID);
}
} catch (Throwable throwable) {
LLog.d(TAG, throwable.getMessage());
StatsStaticHelper.reportOnEvent(a_er, Log.getStackTraceString(throwable));
a.finish();
}
}
private void sendAdShowMessage() {
clearMsg();
}
public void finishs() {
LLog.e(TAG, "finishs: " + isFinished);
if (isFinished) {
return;
}
isFinished = true;
try {
if (messenger != null) {
Message message = Message.obtain();
message.what = 46;
Bundle bundle = new Bundle();
if (node != null) {
bundle.putParcelable("node", node);
}
message.setData(bundle);
messenger.send(message);
LLog.e(TAG, "finishs: 11111111111 node "+node );
}
} catch (Throwable throwable) {
LLog.e(TAG, "finish e: " + Log.getStackTraceString(throwable));
}
}
private void addNodeEvent(Event event) {
if (node != null) {
try {
JSONObject reason = new JSONObject();
reason.put(Constants.TARGET_PKG, cvPkg);
reason.put(Constants.MEDIA_PKG, BaseApplication.getApplication().getPackageName());
reason.put(Constants.REASON, event.reason);
if (TextUtils.isEmpty(appVersionName)) {
appVersionName = PkgUtils.getAppVersionName(BaseApplication.getApplication(), BaseApplication.getApplication().getPackageName());
}
if (TextUtils.isEmpty(appVersionCode)) {
appVersionCode = PkgUtils.getAppVersionCode(BaseApplication.getApplication(), BaseApplication.getApplication().getPackageName());
}
reason.put(VN, appVersionName);
reason.put(VC, appVersionCode);
event.reason = reason.toString();
} catch (Exception e) {
}
node.addEvent(event);
}
}
private static class InterstitialAdCallback implements AdCallback {
private final WeakReference<MainActivity> weakReference;
public InterstitialAdCallback(MainActivity activity) {
weakReference = new WeakReference<>(activity);
}
private void report(String type, String reason) {
MainActivity jojowdDays14 = weakReference.get();
if (jojowdDays14 != null) {
ShowHomeAdUtil showHomeAdUtil = jojowdDays14.getShowHomeAdUtil();
if (null != showHomeAdUtil) {
showHomeAdUtil.report(type, reason);
}
}
}
private void sendAdShowMessage() {
MainActivity jojowdDays14 = weakReference.get();
if (jojowdDays14 != null) {
ShowHomeAdUtil showHomeAdUtil = jojowdDays14.getShowHomeAdUtil();
if (null != showHomeAdUtil) {
showHomeAdUtil.sendAdShowMessage();
}
}
}
@Override
public void onAdLoaded(String type, String ad_type, String reason, long time) {
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
}
@Override
public void onAdShow(String type, String ad_type, String reason, long time) {
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
SplashWindowViewManger.getInstance().removeSplashWindowView(9);
sendAdShowMessage();
}
@Override
public void onAdError(String type, String ad_type, String reason, long time) {
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
}
@Override
public void onAdClick(String type, String ad_type, String reason, long time) {
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
}
@Override
public void onAdClose(String type, String ad_type, String reason, long time) {
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
LLog.w(TAG, "Interstitial close ");
Activity a = weakReference.get();
if (a == null) {
InitA.getInstance().cleanTask(BaseApplication.getApplication());
return;
}
try {
a.startActivity(new Intent(a, TActivity.class));
} catch (Exception e) {
//
}
report(type, "ad_type:" + ad_type + ",reason:" + reason + ",time:" + time);
a.finish();
}
@Override
public void onAdTimeOut(String type, String ad_type, String reason, long time) {
}
}
}
......@@ -5,6 +5,7 @@ import android.util.Log;
import com.gem.media.splash.base.utils.ALog;
import com.or.ange.dot.UsageStats;
import com.or.ange.dot.utils.LLog;
import java.util.HashMap;
import java.util.Map;
......@@ -26,7 +27,7 @@ public class StatsStaticHelper {
params.put("uuid", InitA.getInstance().getUuid());
UsageStats.onEvent(eventId, label, params);
} catch (Exception e) {
ALog.e(TAG,"onEvent 2 e :" + Log.getStackTraceString(e));
LLog.e(TAG,"onEvent 2 e :" + Log.getStackTraceString(e));
}
}
......@@ -36,7 +37,27 @@ public class StatsStaticHelper {
params.put("uuid", InitA.getInstance().getUuid());
UsageStats.onEvent(eventId, "", params);
} catch (Exception e) {
ALog.e(TAG,"onEvent 3 e :" + Log.getStackTraceString(e));
LLog.e(TAG,"onEvent 3 e :" + Log.getStackTraceString(e));
}
}
public static void reportOnEvent(String eventId) {
onEvent(eventId, new HashMap<>());
}
public static void reportOnEvent(String eventId, String label) {
reportOnEvent(eventId, label, new HashMap<>());
}
public static void reportOnEvent(String eventId, String label, Map<String, String> params) {
try {
params.put("uuid", InitA.getInstance().getUuid());
UsageStats.onEvent(eventId, label, params);
} catch (Exception e) {
LLog.e(TAG,"onEvent 2 e :" + Log.getStackTraceString(e));
}
}
}
......@@ -34,7 +34,7 @@ public class SystemDialogReceiver extends BroadcastReceiver {
long currentTime = System.currentTimeMillis();
if (currentTime - lastHomeKeyTime > HOME_KEY_DEBOUNCE_DELAY) {
lastHomeKeyTime = currentTime;
InitA.getInstance().cleanTask(BaseApplication.getApplication(), 0);
InitA.getInstance().cleanTask(BaseApplication.getApplication());
}
break;
}
......
......@@ -100,36 +100,4 @@ public class AdData {
mapHashMap.put(AdData.AD_TYPE_INTERSTITIAL, null);
}
public int getAdIdSize(String adType) {
if (mapHashMap == null || mapHashMap.isEmpty()) {
return -1;
}
List<String> data = mapHashMap.get(adType);
if (data == null || data.isEmpty()) {
return -1;
}
return data.size();
}
public boolean canLoadAdData(String adType) {
boolean can = false;
if (null == adTypes) {
adTypes = new ArrayList<>();
LLog.w("GEM_WZ", " canLoadAdData adTypes == null");
return false;
}
if (TextUtils.isEmpty(adType)) {
return false;
}
LLog.w("GEM_WZ", " canLoadAdData adTypes size == " +adTypes.size());
for (String type : adTypes) {
LLog.w("GEM_WZ", " canLoadAdData adTypes type == " +type +" "+adType);
if (!TextUtils.isEmpty(type) && type.equals(adType)) {
can = true;
break;
}
}
return can;
}
}
......@@ -38,6 +38,7 @@ public class AdManager {
private final Map<String, AdmobNativeManager> admobNativeManagers = new HashMap<>(5);
private boolean canNextAdRequest = true;
public void setCanNextAdRequest(boolean canNextAdRequest) {
......@@ -53,7 +54,6 @@ public class AdManager {
public boolean hasCache() {
return AdmobInterstitialManager.instance().isAdAvailable();
}
public boolean adIsLoading() {
return AdmobInterstitialManager.instance().isAdIsLoading();
}
......@@ -116,7 +116,6 @@ public class AdManager {
}
}
public void setData(JSONArray array) {
if (array == null) {
return;
......@@ -171,6 +170,7 @@ public class AdManager {
admobNativeManagers.put(AdmobNativeManager.P_1, admobNativeManager);
}
}
}
public AdmobNativeManager getAdmobNativeManager(String adPosition) {
......
......@@ -2,12 +2,12 @@ package com.gem.media.ad;
public interface AdStatusCallBack {
void onAdLoad(String type, String ad_type, String reason, long time, String adId, String scenario);
void onAdLoaded(String type, String ad_type, String reason, long time, String adId, String scenario);
void onNoAdError(String type, String ad_type, String reason, long time, String adId, String scenario);
void onAdShow(String type, String ad_type, String reason, long time, String adId, String scenario);
void onAdClick(String type, String ad_type, String reason, long time, String adId, String scenario);
void onAdDismiss(String type, String ad_type, String reason, long time, String adId, String scenario);
void onAdLoadTimeout(String type, String ad_type, String reason, long time, String adId);
void nextMediaAppAdReq(String type, String ad_type, String reason, long time, String adId, String scenario);
}
......@@ -12,7 +12,9 @@ import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.ads.cal.notes.manager.GoogleMobileAdsConsentManager;
import com.gem.media.StatsStaticHelper;
import com.gem.media.splash.base.crash.CountryUtil;
import com.gem.media.splash.base.protocol.AdCallback;
import com.gem.media.splash.base.protocol.Constants;
import com.google.android.gms.ads.AdError;
......@@ -81,7 +83,7 @@ public class AdmobInterstitialManager {
if (null != adStatusCallBack) {
adStatusCallBack.onNoAdError(Constants.NODE_ERROR, AD_TYPE, error, requestTime, mAdUnitId, Constants.SCENARIO_CHAPIN);
}
loadAd(context, loadIndex);
// loadAd(context, loadIndex);
}
@Override
......@@ -99,7 +101,7 @@ public class AdmobInterstitialManager {
adStatusCallBack.onAdLoaded(Constants.NODE_REQUEST_SUCCESS, AD_TYPE, "loaded", requestTime, mAdUnitId, Constants.SCENARIO_CHAPIN);
}
requestTime = System.currentTimeMillis();
loadIndex = 0;
// loadIndex = 0;
}
});
......@@ -210,28 +212,16 @@ public class AdmobInterstitialManager {
public void loadAd(Context context, int loadIndex) {
if (context == null) {
if (null != adStatusCallBack) {
adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "context is null", -2, "", Constants.SCENARIO_CHAPIN);
}
return;
}
if (null != adStatusCallBack) {
adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "loadAd admob chaping start", -2, "", Constants.SCENARIO_CHAPIN);
}
LLog.d(TAG, "loadAd admob chaping start.");
if (adIsLoading) {
LLog.d(TAG, "loadAd admob isLoading. "+AdmobInterstitialManager.mAdUnitId);
if (null != adStatusCallBack) {
adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "adIsLoading", -2, AdmobInterstitialManager.mAdUnitId, Constants.SCENARIO_CHAPIN);
}
return;
}
if (isAdAvailable()) {
LLog.d(TAG, "loadAd admob chaping 3.");
if (null != adStatusCallBack) {
adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "has cache", -2, AdmobInterstitialManager.mAdUnitId, Constants.SCENARIO_CHAPIN);
}
return;
}
......@@ -239,42 +229,31 @@ public class AdmobInterstitialManager {
AdData adData = CpAdData.getInstance().getAdData(CP_ADMOB);
if (adData == null) {
LLog.w(TAG, " adData = null");
if (null != adStatusCallBack) {
adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "adData = null", -1, "", Constants.SCENARIO_CHAPIN);
}
return;
}
AdmobInterstitialManager.mAdUnitId = adData.getAdAdId(AdData.AD_TYPE_INTERSTITIAL, loadIndex);
if (TextUtils.isEmpty(AdmobInterstitialManager.mAdUnitId)) {
LLog.d(TAG, "loadAd admob chaping AdUnitId is empty loadIndex = "+loadIndex);
if (null != adStatusCallBack) {
adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "AdUnitId is empty loadIndex = " + loadIndex, -1, "", Constants.SCENARIO_CHAPIN);
}
this.loadIndex = 0;
return;
}
if (isScreenLock(context)) {
LLog.d(TAG, "loadAd admob chaping 1.");
if (null != adStatusCallBack) {
adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "isScreenLock", -2, AdmobInterstitialManager.mAdUnitId, Constants.SCENARIO_CHAPIN);
}
return;
}
if (!isScreenOn(context)) {
LLog.d(TAG, "loadAd admob chaping 2.");
if (null != adStatusCallBack) {
adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "isScreenOff", -2, AdmobInterstitialManager.mAdUnitId, Constants.SCENARIO_CHAPIN);
}
return;
}
// if (!GoogleMobileAdsConsentManager.getInstance(context).canRequestAds()) {
if (!GoogleMobileAdsConsentManager.getInstance(context).canRequestAds()) {
// LLog.d(TAG, "loadAd admob chaping canRequestAds false.");
// if (null != adStatusCallBack) {
// adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "canRequestAds false" , -1, AdmobInterstitialManager.mAdUnitId, Constants.SCENARIO_CHAPIN);
// }
try {
String country = CountryUtil.getLocalCountry(context);
StatsStaticHelper.onEvent("adC", country);
} catch (Exception e) {
}
// return;
// }
this.loadIndex = loadIndex + 1;
}
loadInterstitial(context, mAdUnitId);
} catch (Exception e) {
LLog.d(TAG, "loadAd chaping. e ----" + e.getMessage());
......
......@@ -57,126 +57,126 @@ public class AdmobNativeManager {
adIsLoading = true;
builder.forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
// OnLoadedListener implementation.
@Override
public void onNativeAdLoaded(NativeAd nativeAd) {
adIsLoading = false;
// If this callback occurs after the activity is destroyed, you must call
// destroy and return or you may get a memory leak.
// OnLoadedListener implementation.
@Override
public void onNativeAdLoaded(NativeAd nativeAd) {
adIsLoading = false;
// If this callback occurs after the activity is destroyed, you must call
// destroy and return or you may get a memory leak.
// boolean isDestroyed = false;
// isDestroyed = isDestroyed();
// if (isDestroyed || isFinishing() || isChangingConfigurations()) {
// nativeAd.destroy();
// return;
// }
// You must call destroy on old ads when you are done with them,
// otherwise you will have a memory leak.
LLog.d(TAG, "onNativeAdLoaded.");
if (mNativeAd != null) {
mNativeAd.destroy();
}
mNativeAd = nativeAd;
// You must call destroy on old ads when you are done with them,
// otherwise you will have a memory leak.
LLog.d(TAG, "onNativeAdLoaded.");
if (mNativeAd != null) {
mNativeAd.destroy();
}
mNativeAd = nativeAd;
adIsLoading = false;
loadAdTime = (new Date()).getTime();
requestTime = System.currentTimeMillis() - requestTime;
if (null != adCallback) {
adCallback.onAdLoaded(Constants.NODE_REQUEST_SUCCESS_EID, AD_TYPE, "loaded", requestTime);
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdLoaded(Constants.NODE_REQUEST_SUCCESS, AD_TYPE, "loaded", requestTime, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR, adPosition);
}
requestTime = System.currentTimeMillis();
loadIndex = 0;
}
});
adIsLoading = false;
loadAdTime = (new Date()).getTime();
requestTime = System.currentTimeMillis() - requestTime;
if (null != adCallback) {
adCallback.onAdLoaded(Constants.NODE_REQUEST_SUCCESS_EID, AD_TYPE, "loaded", requestTime);
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdLoaded(Constants.NODE_REQUEST_SUCCESS, AD_TYPE, "loaded", requestTime, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR, adPosition);
}
requestTime = System.currentTimeMillis();
loadIndex = 0;
}
});
VideoOptions videoOptions = new VideoOptions.Builder().setStartMuted(true).build();
NativeAdOptions adOptions = new NativeAdOptions.Builder().setVideoOptions(videoOptions).build();
builder.withNativeAdOptions(adOptions);
AdLoader adLoader = builder.withAdListener(new AdListener() {
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
adIsLoading = false;
String error = String.format(
Locale.getDefault(),
"domain: %s, code: %d, message: %s",
loadAdError.getDomain(),
loadAdError.getCode(),
loadAdError.getMessage());
LLog.d(TAG, "error. "+error);
requestTime = System.currentTimeMillis() - requestTime;
if (null != adCallback) {
adCallback.onAdError(Constants.NODE_ERROR_EID, AD_TYPE, error, requestTime);
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onNoAdError(Constants.NODE_ERROR, AD_TYPE, error, requestTime, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR);
}
loadAd(context, loadIndex);
}
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
adIsLoading = false;
String error = String.format(
Locale.getDefault(),
"domain: %s, code: %d, message: %s",
loadAdError.getDomain(),
loadAdError.getCode(),
loadAdError.getMessage());
LLog.d(TAG, "error. "+error);
requestTime = System.currentTimeMillis() - requestTime;
if (null != adCallback) {
adCallback.onAdError(Constants.NODE_ERROR_EID, AD_TYPE, error, requestTime);
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onNoAdError(Constants.NODE_ERROR, AD_TYPE, error, requestTime, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR);
}
loadAd(context, loadIndex);
}
@Override
public void onAdImpression() {
super.onAdImpression();
LLog.d(TAG, "onAdImpression.");
if (null != adCallback) {
adCallback.onAdShow(Constants.NODE_SHOW_EID, AD_TYPE, "", -1);
adCallback = null;
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdShow(Constants.NODE_SHOW, AD_TYPE, "", -1, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR);
}
}
@Override
public void onAdImpression() {
super.onAdImpression();
LLog.d(TAG, "onAdImpression.");
if (null != adCallback) {
adCallback.onAdShow(Constants.NODE_SHOW_EID, AD_TYPE, "", -1);
adCallback = null;
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdShow(Constants.NODE_SHOW, AD_TYPE, "", -1, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR);
}
}
@Override
public void onAdClicked() {
super.onAdClicked();
LLog.d(TAG, "onAdClicked.");
if (null != adCallback) {
adCallback.onAdClick(Constants.NODE_CLICK_EID, AD_TYPE, "click", -1);
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdClick(Constants.NODE_CLICK, AD_TYPE, "click", -1, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR);
}
}
@Override
public void onAdClicked() {
super.onAdClicked();
LLog.d(TAG, "onAdClicked.");
if (null != adCallback) {
adCallback.onAdClick(Constants.NODE_CLICK_EID, AD_TYPE, "click", -1);
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdClick(Constants.NODE_CLICK, AD_TYPE, "click", -1, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR);
}
}
@Override
public void onAdOpened() {
super.onAdOpened();
if (null != adCallback) {
adCallback.onAdClick(Constants.NODE_OPEN_EID, AD_TYPE, "open", -1);
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdClick(Constants.NODE_OPEN, AD_TYPE, "open", -1, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR);
}
}
@Override
public void onAdOpened() {
super.onAdOpened();
if (null != adCallback) {
adCallback.onAdClick(Constants.NODE_OPEN_EID, AD_TYPE, "open", -1);
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdClick(Constants.NODE_OPEN, AD_TYPE, "open", -1, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR);
}
}
@Override
public void onAdLoaded() {
super.onAdLoaded();
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdLoaded(Constants.NODE_OPEN, AD_TYPE, "open", -1, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR, adPosition);
}
LLog.d(TAG, "onAdLoaded. 0000000");
}
@Override
public void onAdLoaded() {
super.onAdLoaded();
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdLoaded(Constants.NODE_OPEN, AD_TYPE, "open", -1, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR, adPosition);
}
LLog.d(TAG, "onAdLoaded. 0000000");
}
@Override
public void onAdClosed() {
super.onAdClosed();
LLog.d(TAG, "onAdClosed.");
if (null != adCallback) {
adCallback.onAdClose(Constants.NODE_CLOSE_EID, AD_TYPE, "", -1);
adCallback = null;
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdDismiss(Constants.NODE_CLOSE, AD_TYPE, "", -1, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR);
}
}
@Override
public void onAdClosed() {
super.onAdClosed();
LLog.d(TAG, "onAdClosed.");
if (null != adCallback) {
adCallback.onAdClose(Constants.NODE_CLOSE_EID, AD_TYPE, "", -1);
adCallback = null;
}
if (null != nativeAdStatusCallBack) {
nativeAdStatusCallBack.onAdDismiss(Constants.NODE_CLOSE, AD_TYPE, "", -1, mAdUnitId, Constants.SCENARIO_NATIVE_CLEAR);
}
}
@Override
public void onAdSwipeGestureClicked() {
super.onAdSwipeGestureClicked();
}
}).build();
@Override
public void onAdSwipeGestureClicked() {
super.onAdSwipeGestureClicked();
}
}).build();
adLoader.loadAd(new AdRequest.Builder().build());
}
......
......@@ -9,7 +9,6 @@ import com.gem.media.InitA;
import java.util.HashMap;
public class CpAdData {
private static boolean isInit = false;
private static final class CpAdDataHolder {
static final CpAdData adManager = new CpAdData();
......@@ -19,11 +18,10 @@ public class CpAdData {
return CpAdDataHolder.adManager;
}
private static HashMap<String, AdData> adDataHashMap = new HashMap<>();
private HashMap<String, AdData> adDataHashMap;
public static final String CP_ADMOB = "admob";
public void setCpData(String cp, AdData adData) {
if (null == adDataHashMap) {
adDataHashMap = new HashMap<>();
......@@ -57,5 +55,4 @@ public class CpAdData {
}
}
}
package com.gem.media.ad.service;
import static com.gem.media.ad.CpAdData.CP_ADMOB;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
......@@ -25,14 +27,29 @@ import com.gem.media.ad.AdManager;
import com.gem.media.ad.AdmobInterstitialManager;
import com.gem.media.ad.CpAdData;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.util.GKpLiveHelper;
import com.gem.media.util.SplashWindowViewManger;
import com.live.KpUtil;
import com.or.ange.dot.utils.LLog;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyDataService extends Service {
private static final String TAG = "MyAdService";
private static final int NEW_CONTENT_VERSION_CODE = 1;
private static final int MSG_WHAT = 1234;
private static final int MSG_WHAT2 = 1235;
private static final int MSG_WHAT3 = 1236;
private static final int MSG_WHAT4 = 1237;
private static final int MSG_WHAT7 = 1240;
private static final int MSG_WHAT8 = 1241;
private static final int MSG_WHAT9 = 1242;
private static final String PARAM_DATA = "adData";
public static final String PARAM_CPID = "cpId";
public static final String PARAM_APPID_CHANNELID = "adAppId_channelId";
......@@ -40,17 +57,52 @@ public class MyDataService extends Service {
public static final String PARAM_ADID = "adId";
public static final String PARAM_CHANNELID= "channelId";
private static final String NEW_DEX_VERSION = "1";
private static final String PARAM_C_PKG_NAME= "c_pkgName";
private static final String PARAM_PATH_BG= "pathBg";
private static final String PARAM_CLOSE_TIME= "closeTime";
private static final String PARAM_C = "c";
private static final int AD_DATA_TYPE = 2;
public static final String T_ = "_";
private static final int NEW_CONTENT_VERSION_CODE = 1;
private static final int MSG_WHAT3 = 1236;
private static final int MSG_WHAT4 = 1237;
private static final Handler handler = new Handler(Looper.getMainLooper()) {
private static final ExecutorService executorService = Executors.newSingleThreadExecutor();
private static final Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_WHAT:
try {
Bundle bundle = msg.getData();
if (null != bundle) {
String cpId = bundle.getString(PARAM_CPID);
String adAppId_channelId = bundle.getString(PARAM_APPID_CHANNELID);
String adType = bundle.getString(PARAM_AD_TYPE);
String adId = bundle.getString(PARAM_ADID);
setData(cpId, adAppId_channelId, adType, adId);
}
} catch (Throwable e) {
String er = Log.getStackTraceString(e);
LLog.w(TAG, er);
}
break;
case MSG_WHAT2:
try {
Bundle bundle2 = msg.getData();
if (null != bundle2) {
String channelId = bundle2.getString(PARAM_CHANNELID);
if (TextUtils.isEmpty(channelId)) {
channelId = InitA.DEFAULT_APP_ID;
}
// LLog.w(TAG, "initMediaApp " + channelId);
InitA.getInstance().initMediaApp(channelId);
KpUtil.getInstance().startLive(BaseApplication.getApplication());
}
} catch (Throwable e) {
String er = Log.getStackTraceString(e);
LLog.w(TAG, er);
}
break;
case MSG_WHAT3:
try {
InitA.getInstance().closeActivity(2);
......@@ -59,48 +111,73 @@ public class MyDataService extends Service {
LLog.w(TAG, er);
}
break;
case MSG_WHAT4:
Bundle bundle4 = msg.getData();
if (null != bundle4) {
String data = bundle4.getString(PARAM_DATA, "");
if (data == null || data.isEmpty()) {
return;
case MSG_WHAT7:
try {
Bundle bundle3 = msg.getData();
if (null != bundle3) {
String c_pkgName = bundle3.getString(PARAM_C_PKG_NAME);
String pathBg = bundle3.getString(PARAM_PATH_BG);
long closeTime = bundle3.getLong(PARAM_CLOSE_TIME);
SplashWindowViewManger.getInstance().showSplashWindowView(c_pkgName, pathBg, closeTime);
}
try {
AdData adData = CpAdData.getInstance().getAdData(CpAdData.CP_ADMOB);
if (adData != null) {
adData.clearAdIdData();
}
} catch (Exception e) {
} catch (Throwable e) {
String er = Log.getStackTraceString(e);
ALog.w(TAG, er);
}
break;
case MSG_WHAT8:
try {
SplashWindowViewManger.getInstance().removeSplashWindowView(8);
} catch (Throwable e) {
String er = Log.getStackTraceString(e);
ALog.w(TAG, er);
}
break;
case MSG_WHAT9:
try {
Bundle bundle9 = msg.getData();
if (null != bundle9) {
String c = bundle9.getString(PARAM_C);
if (!TextUtils.isEmpty(c)) {
// if (!KpUtil.getInstance().isBindGpService()) {
// return;
// }
// KpUtil.getInstance().bindKpLiveService(c);
Message message = Message.obtain();
Bundle bundle5 = new Bundle();
bundle5.putString(PARAM_C, c);
message.setData(bundle5);
message.what = MSG_WHAT9;
// handler.sendMessageDelayed(message, T);
}
}
try {
JSONArray array = new JSONArray(data);
AdManager.getInstance().setData(array);
} catch (JSONException e) {
//
}
} catch (Throwable e) {
String er = Log.getStackTraceString(e);
ALog.w(TAG, er);
}
break;
default:
break;
}
}
};
@Override
public void onCreate() {
super.onCreate();
ALog.d(TAG, "onCreate");
Log.d(TAG, "onCreate");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
ALog.d(TAG, "onBind");
Log.d(TAG, "onBind");
return binder;
}
private static final AdServiceBinder binder = new AdServiceBinder();
public static class AdServiceBinder extends XGENAdData.Stub {
......@@ -109,6 +186,36 @@ public class MyDataService extends Service {
@Override
public void setAdData(String cpId, String adAppId_channelId, String adType, String appKey, String adId) throws RemoteException {
Log.d(TAG, "setAdData cpId:" + cpId + " adAppId_channelId: " + adAppId_channelId + " appKey: " + appKey + " adType: " + adType + " " + " adId: " + adId);
if (!InitA.getInstance().isAppBackground()) {
return;
}
try {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
handler.removeMessages(MSG_WHAT);
//"a6501757a165c4"
LLog.w(TAG, "setAdData cpId:" + cpId + " adAppId_channelId: " + adAppId_channelId + " appKey: " + appKey + " adType: " + adType + " " + " adId: " + adId);
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString(PARAM_CPID, cpId);
bundle.putString(PARAM_APPID_CHANNELID, adAppId_channelId);
bundle.putString(PARAM_AD_TYPE, adType);
bundle.putString(PARAM_ADID, adId);
message.setData(bundle);
message.what = MSG_WHAT;
handler.sendMessage(message);
} catch (Exception e) {
//
}
}
});
} catch (Exception e) {
//
}
}
@Override
......@@ -121,11 +228,6 @@ public class MyDataService extends Service {
return AdManager.getInstance().hasCache();
}
@Override
public boolean adIsLoading() throws RemoteException {
return AdManager.getInstance().adIsLoading();
}
@Override
public int newContentVersionCode() throws RemoteException {
return NEW_CONTENT_VERSION_CODE;
......@@ -137,99 +239,137 @@ public class MyDataService extends Service {
}
@Override
public void setUuid(String uuid) throws RemoteException {
ALog.w(TAG, "setUuid " + uuid );
public void setUuid(String uuid) throws RemoteException {
InitA.getInstance().setUuid(uuid);
}
@Override
public void setAlertWindowOpen(boolean open) throws RemoteException {
ALog.w(TAG, "setAlertWindowOpen " + open );
}
public void initMediaApp(String channelId) throws RemoteException {
try {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString(PARAM_CHANNELID, channelId);
message.setData(bundle);
handler.removeMessages(MSG_WHAT2);
message.what = MSG_WHAT2;
handler.sendMessage(message);
GKpLiveHelper.getInstance().init();
} catch (Exception e) {
@Override
public void initMediaApp(String channelId) throws RemoteException {
String value = null;
if (channelId.contains("_")) {
String[] s = channelId.split("_");
if (s.length > 1) {
value = s[1];
}
} else {
value = channelId;
}
}
});
} catch (Exception e) {
//
}
ALog.w(TAG, "initMediaApp " + value );
InitA.getInstance().initMediaApp(value);
}
@Override
public void closeActivity() throws RemoteException {
handler.removeMessages(MSG_WHAT3);
handler.sendEmptyMessage(MSG_WHAT3);
public void closeActivity() throws RemoteException {
try {
handler.removeMessages(MSG_WHAT3);
executorService.submit(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(MSG_WHAT3);
}
});
} catch (Exception e) {
//
}
}
@Override
public void showNAd() throws RemoteException {
ALog.w(TAG, "showNAd " );
}
@Override
public void showInterstitialHalfAd() throws RemoteException {
ALog.w(TAG, "showInterstitialHalfAd " );
}
@Override
public void closeNAd() throws RemoteException {
ALog.w(TAG, "clsoeNAd " );
}
@Override
public void setNCanNextRequestAd(boolean can) throws RemoteException {
ALog.w(TAG, "setNCanNextRequestAd can = " + can );
// LLog.w(TAG, "setNCanNextRequestAd can = " + can);
}
@Override
public void transferData(int type, String data) {
if (null == data || data.isEmpty()) {
ALog.d(TAG, "parseData is null");
return;
public void showSplashBg(String c_pkgName, String pathBg, long closeTime) throws RemoteException {
try {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
// ALog.w(TAG, "showSplashBg c_pkgName = " + c_pkgName + " closeTime = " + closeTime);
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString(PARAM_C_PKG_NAME, c_pkgName);
bundle.putString(PARAM_PATH_BG, pathBg);
bundle.putLong(PARAM_CLOSE_TIME, closeTime);
message.setData(bundle);
handler.removeMessages(MSG_WHAT7);
message.what = MSG_WHAT7;
handler.sendMessage(message);
} catch (Exception e) {
}
}
});
} catch (Exception e) {
//
}
parseData(type, data);
}
private void parseData(int type, String data) {
ALog.d(TAG, "parseData type = " +type + " data =" + data);
switch (type) {
case AD_DATA_TYPE:
if (!InitA.getInstance().isAppBackground()) {
return;
@Override
public void closeSplashBg() {
try {
handler.removeMessages(MSG_WHAT8);
executorService.submit(new Runnable() {
@Override
public void run() {
handler.removeMessages(MSG_WHAT8);
handler.sendEmptyMessage(MSG_WHAT8);
}
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString(PARAM_DATA, data);
message.setData(bundle);
message.what = MSG_WHAT4;
handler.sendMessage(message);
break;
default:
break;
});
} catch (Exception e) {
//
}
}
}
// private static String cpId;
// private static String adAppId_channelId;
// private static String appkey;
// private static String adType;
// private static String adId;
@Override
public void startKp(boolean start, boolean startGp) {
private static void setData(String cpId, String adAppId_channelId, String appKey, String adType, String adId) {
ALog.w(TAG, "cpId = "+cpId+" adAppId_channelId " + adAppId_channelId + " adType " + adType + " adId " + adId);
}
@Override
public void startKp2(int start, int startGp) {
KpUtil.getInstance().setStartKpLive(start, startGp);
}
@Override
public void setReportS(int i) {
InitA.setReportSwitch(i);
}
}
private static void setData(String cpId, String adAppId_channelId, String adType, String adId) {
LLog.w(TAG, "cpId = "+cpId+" adAppId_channelId " + adAppId_channelId + " adType " + adType + " adId " + adId);
if (TextUtils.isEmpty(cpId)) {
return;
}
if (!CpAdData.CP_ADMOB.equals(cpId)) {
if (!CP_ADMOB.equals(cpId)) {
return;
}
AdData adData = CpAdData.getInstance().getAdData(cpId);
......@@ -243,18 +383,6 @@ public class MyDataService extends Service {
AdmobInterstitialManager.instance().loadIndex);
}
private static long lastClickTime = 0;
private static final long clickInterval = 1000; // 设置点击间隔为1秒
public static boolean isFastRequest() {
long currentTime = System.currentTimeMillis();
if (currentTime - lastClickTime >= clickInterval) {
lastClickTime = currentTime;
return false;
}
lastClickTime = currentTime;
return true;
}
}
package com.gem.media.splash.base.crash;
import android.util.Log;
import com.or.ange.dot.utils.LLog;
public class AESEncryptUtil {
private static final String sSecretKey = "b1ac9861485a652b";
private static final String iv = "1269571569321210";
public static byte[] encrypt2(String strToEncrypt) {
if (null == strToEncrypt) {
LLog.d("AESEncryptUtil: " , "strToEncrypt is null");
return new byte[0];
}
try {
return AesUtils.encryptString(sSecretKey, iv, strToEncrypt);
} catch (Exception e) {
LLog.d("AESEncryptUtil: " , e.toString());
}
return new byte[0];
}
public static String decrypt2(String strToDecrypt) {
if (null == strToDecrypt) {
LLog.d("AESEncryptUtil: " , "strToDecrypt is null");
return "";
}
try {
AesCodeC aesCodeC = new AesCodeC(iv, sSecretKey);
return aesCodeC.decode(strToDecrypt);
} catch (Throwable e) {
LLog.d("AESEncryptUtil: " , Log.getStackTraceString(e));
}
return "";
}
}
package com.gem.media.splash.base.crash;
import android.util.Base64;
public class AesCodeC{
private final String iv;
private final String key;
public AesCodeC(String iv, String key) {
this.iv = iv;
this.key = key;
}
public String decode(String encContent) throws Throwable {
return decryptContent(encContent);
}
private String decryptContent(String responseContent) throws Exception {
responseContent = trimEncryptContent(responseContent);
byte[] decode = Base64.decode(responseContent, Base64.NO_WRAP);
decode = AesUtils.decryptByte(key, iv, decode);
return new String(decode, "utf-8");
}
private String trimEncryptContent(String responseContent) {
if (responseContent.startsWith("\"")) {
responseContent = responseContent.substring(1);
}
if (responseContent.endsWith("\"")) {
responseContent = responseContent.substring(0, responseContent.length() - 1);
}
return responseContent;
}
}
package com.gem.media.splash.base.crash;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AesUtils {
private static final String AES = "AES";
private static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5Padding";
public static byte[] encryptString(String key, String iv, String cleartext)
throws Exception {
return encryptByte(key, iv, cleartext.getBytes("utf-8"));
}
public static byte[] decryptByte(String key, String iv, byte[] encrypted)
throws Exception {
Cipher cipher = initAESCipher(key, iv, Cipher.DECRYPT_MODE);
return cipher.doFinal(encrypted);
}
public static byte[] encryptByte(String key, String iv, byte[] clear)
throws Exception {
Cipher cipher = initAESCipher(key, iv, Cipher.ENCRYPT_MODE);
return cipher.doFinal(clear);
}
public static Cipher initAESCipher(String key, String iv, int cipherMode)
throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes("utf-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("utf-8"), AES);
Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING);
cipher.init(cipherMode, skeySpec, zeroIv);
return cipher;
}
}
package com.gem.media.splash.base.crash;
/*
* Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/**
* 文件复制于android27的Base64.java
*
* This class consists exclusively of static methods for obtaining
* encoders and decoders for the Base64 encoding scheme. The
* implementation of this class supports the following types of Base64
* as specified in
* <a href="http://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a> and
* <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
*
* <ul>
* <li><a name="basic"><b>Basic</b></a>
* <p> Uses "The Base64 Alphabet" as specified in Table 1 of
* RFC 4648 and RFC 2045 for encoding and decoding operation.
* The encoder does not add any line feed (line separator)
* character. The decoder rejects data that contains characters
* outside the base64 alphabet.</p></li>
*
* <li><a name="url"><b>URL and Filename safe</b></a>
* <p> Uses the "URL and Filename safe Base64 Alphabet" as specified
* in Table 2 of RFC 4648 for encoding and decoding. The
* encoder does not add any line feed (line separator) character.
* The decoder rejects data that contains characters outside the
* base64 alphabet.</p></li>
*
* <li><a name="mime"><b>MIME</b></a>
* <p> Uses the "The Base64 Alphabet" as specified in Table 1 of
* RFC 2045 for encoding and decoding operation. The encoded output
* must be represented in lines of no more than 76 characters each
* and uses a carriage return {@code '\r'} followed immediately by
* a linefeed {@code '\n'} as the line separator. No line separator
* is added to the end of the encoded output. All line separators
* or other characters not found in the base64 alphabet table are
* ignored in decoding operation.</p></li>
* </ul>
*
* <p> Unless otherwise noted, passing a {@code null} argument to a
* method of this class will cause a {@link NullPointerException
* NullPointerException} to be thrown.
*
* @author Xueming Shen
* @since 1.8
*/
public class AndroidOBase64 {
private AndroidOBase64() {}
/**
* Returns a {@link Encoder} that encodes using the
* <a href="#basic">Basic</a> type base64 encoding scheme.
*
* @return A Base64 encoder.
*/
public static Encoder getEncoder() {
return Encoder.RFC4648;
}
/**
* Returns a {@link Encoder} that encodes using the
* <a href="#url">URL and Filename safe</a> type base64
* encoding scheme.
*
* @return A Base64 encoder.
*/
public static Encoder getUrlEncoder() {
return Encoder.RFC4648_URLSAFE;
}
/**
* Returns a {@link Encoder} that encodes using the
* <a href="#mime">MIME</a> type base64 encoding scheme.
*
* @return A Base64 encoder.
*/
public static Encoder getMimeEncoder() {
return Encoder.RFC2045;
}
/**
* Returns a {@link Encoder} that encodes using the
* <a href="#mime">MIME</a> type base64 encoding scheme
* with specified line length and line separators.
*
* @param lineLength
* the length of each output line (rounded down to nearest multiple
* of 4). If {@code lineLength <= 0} the output will not be separated
* in lines
* @param lineSeparator
* the line separator for each output line
*
* @return A Base64 encoder.
*
* @throws IllegalArgumentException if {@code lineSeparator} includes any
* character of "The Base64 Alphabet" as specified in Table 1 of
* RFC 2045.
*/
public static Encoder getMimeEncoder(int lineLength, byte[] lineSeparator) {
Objects.requireNonNull(lineSeparator);
int[] base64 = Decoder.fromBase64;
for (byte b : lineSeparator) {
if (base64[b & 0xff] != -1)
throw new IllegalArgumentException(
"Illegal base64 line separator character 0x" + Integer.toString(b, 16));
}
if (lineLength <= 0) {
return Encoder.RFC4648;
}
return new Encoder(false, lineSeparator, lineLength >> 2 << 2, true);
}
/**
* Returns a {@link Decoder} that decodes using the
* <a href="#basic">Basic</a> type base64 encoding scheme.
*
* @return A Base64 decoder.
*/
public static Decoder getDecoder() {
return Decoder.RFC4648;
}
/**
* Returns a {@link Decoder} that decodes using the
* <a href="#url">URL and Filename safe</a> type base64
* encoding scheme.
*
* @return A Base64 decoder.
*/
public static Decoder getUrlDecoder() {
return Decoder.RFC4648_URLSAFE;
}
/**
* Returns a {@link Decoder} that decodes using the
* <a href="#mime">MIME</a> type base64 decoding scheme.
*
* @return A Base64 decoder.
*/
public static Decoder getMimeDecoder() {
return Decoder.RFC2045;
}
/**
* This class implements an encoder for encoding byte data using
* the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
*
* <p> Instances of {@link Encoder} class are safe for use by
* multiple concurrent threads.
*
* <p> Unless otherwise noted, passing a {@code null} argument to
* a method of this class will cause a
* {@link NullPointerException NullPointerException} to
* be thrown.
*
* @see Decoder
* @since 1.8
*/
public static class Encoder {
private final byte[] newline;
private final int linemax;
private final boolean isURL;
private final boolean doPadding;
private Encoder(boolean isURL, byte[] newline, int linemax, boolean doPadding) {
this.isURL = isURL;
this.newline = newline;
this.linemax = linemax;
this.doPadding = doPadding;
}
/**
* This array is a lookup table that translates 6-bit positive integer
* index values into their "Base64 Alphabet" equivalents as specified
* in "Table 1: The Base64 Alphabet" of RFC 2045 (and RFC 4648).
*/
private static final char[] toBase64 = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
/**
* It's the lookup table for "URL and Filename safe Base64" as specified
* in Table 2 of the RFC 4648, with the '+' and '/' changed to '-' and
* '_'. This table is used when BASE64_URL is specified.
*/
private static final char[] toBase64URL = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
};
private static final int MIMELINEMAX = 76;
private static final byte[] CRLF = new byte[] {'\r', '\n'};
static final Encoder RFC4648 = new Encoder(false, null, -1, true);
static final Encoder RFC4648_URLSAFE = new Encoder(true, null, -1, true);
static final Encoder RFC2045 = new Encoder(false, CRLF, MIMELINEMAX, true);
private final int outLength(int srclen) {
int len = 0;
if (doPadding) {
len = 4 * ((srclen + 2) / 3);
} else {
int n = srclen % 3;
len = 4 * (srclen / 3) + (n == 0 ? 0 : n + 1);
}
if (linemax > 0) // line separators
len += (len - 1) / linemax * newline.length;
return len;
}
/**
* Encodes all bytes from the specified byte array into a newly-allocated
* byte array using the {@link AndroidOBase64} encoding scheme. The returned byte
* array is of the length of the resulting bytes.
*
* @param src
* the byte array to encode
* @return A newly-allocated byte array containing the resulting
* encoded bytes.
*/
public byte[] encode(byte[] src) {
int len = outLength(src.length); // dst array size
byte[] dst = new byte[len];
int ret = encode0(src, 0, src.length, dst);
if (ret != dst.length)
return Arrays.copyOf(dst, ret);
return dst;
}
/**
* Encodes all bytes from the specified byte array using the
* {@link AndroidOBase64} encoding scheme, writing the resulting bytes to the
* given output byte array, starting at offset 0.
*
* <p> It is the responsibility of the invoker of this method to make
* sure the output byte array {@code dst} has enough space for encoding
* all bytes from the input byte array. No bytes will be written to the
* output byte array if the output byte array is not big enough.
*
* @param src
* the byte array to encode
* @param dst
* the output byte array
* @return The number of bytes written to the output byte array
*
* @throws IllegalArgumentException if {@code dst} does not have enough
* space for encoding all input bytes.
*/
public int encode(byte[] src, byte[] dst) {
int len = outLength(src.length); // dst array size
if (dst.length < len)
throw new IllegalArgumentException(
"Output byte array is too small for encoding all input bytes");
return encode0(src, 0, src.length, dst);
}
/**
* Encodes the specified byte array into a String using the {@link AndroidOBase64}
* encoding scheme.
*
* <p> This method first encodes all input bytes into a base64 encoded
* byte array and then constructs a new String by using the encoded byte
* array and the {@link StandardCharsets#ISO_8859_1
* ISO-8859-1} charset.
*
* <p> In other words, an invocation of this method has exactly the same
* effect as invoking
* {@code new String(encode(src), StandardCharsets.ISO_8859_1)}.
*
* @param src
* the byte array to encode
* @return A String containing the resulting Base64 encoded characters
*/
@SuppressWarnings("deprecation")
public String encodeToString(byte[] src) {
byte[] encoded = encode(src);
return new String(encoded, 0, 0, encoded.length);
}
/**
* Encodes all remaining bytes from the specified byte buffer into
* a newly-allocated ByteBuffer using the {@link AndroidOBase64} encoding
* scheme.
*
* Upon return, the source buffer's position will be updated to
* its limit; its limit will not have been changed. The returned
* output buffer's position will be zero and its limit will be the
* number of resulting encoded bytes.
*
* @param buffer
* the source ByteBuffer to encode
* @return A newly-allocated byte buffer containing the encoded bytes.
*/
public ByteBuffer encode(ByteBuffer buffer) {
int len = outLength(buffer.remaining());
byte[] dst = new byte[len];
int ret = 0;
if (buffer.hasArray()) {
ret = encode0(buffer.array(),
buffer.arrayOffset() + buffer.position(),
buffer.arrayOffset() + buffer.limit(),
dst);
buffer.position(buffer.limit());
} else {
byte[] src = new byte[buffer.remaining()];
buffer.get(src);
ret = encode0(src, 0, src.length, dst);
}
if (ret != dst.length)
dst = Arrays.copyOf(dst, ret);
return ByteBuffer.wrap(dst);
}
/**
* Wraps an output stream for encoding byte data using the {@link AndroidOBase64}
* encoding scheme.
*
* <p> It is recommended to promptly close the returned output stream after
* use, during which it will flush all possible leftover bytes to the underlying
* output stream. Closing the returned output stream will close the underlying
* output stream.
*
* @param os
* the output stream.
* @return the output stream for encoding the byte data into the
* specified Base64 encoded format
*/
public OutputStream wrap(OutputStream os) {
Objects.requireNonNull(os);
return new EncOutputStream(os, isURL ? toBase64URL : toBase64,
newline, linemax, doPadding);
}
/**
* Returns an encoder instance that encodes equivalently to this one,
* but without adding any padding character at the end of the encoded
* byte data.
*
* <p> The encoding scheme of this encoder instance is unaffected by
* this invocation. The returned encoder instance should be used for
* non-padding encoding operation.
*
* @return an equivalent encoder that encodes without adding any
* padding character at the end
*/
public Encoder withoutPadding() {
if (!doPadding)
return this;
return new Encoder(isURL, newline, linemax, false);
}
private int encode0(byte[] src, int off, int end, byte[] dst) {
char[] base64 = isURL ? toBase64URL : toBase64;
int sp = off;
int slen = (end - off) / 3 * 3;
int sl = off + slen;
if (linemax > 0 && slen > linemax / 4 * 3)
slen = linemax / 4 * 3;
int dp = 0;
while (sp < sl) {
int sl0 = Math.min(sp + slen, sl);
for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) {
int bits = (src[sp0++] & 0xff) << 16 |
(src[sp0++] & 0xff) << 8 |
(src[sp0++] & 0xff);
dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f];
dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f];
dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f];
dst[dp0++] = (byte)base64[bits & 0x3f];
}
int dlen = (sl0 - sp) / 3 * 4;
dp += dlen;
sp = sl0;
if (dlen == linemax && sp < end) {
for (byte b : newline){
dst[dp++] = b;
}
}
}
if (sp < end) { // 1 or 2 leftover bytes
int b0 = src[sp++] & 0xff;
dst[dp++] = (byte)base64[b0 >> 2];
if (sp == end) {
dst[dp++] = (byte)base64[(b0 << 4) & 0x3f];
if (doPadding) {
dst[dp++] = '=';
dst[dp++] = '=';
}
} else {
int b1 = src[sp++] & 0xff;
dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)];
dst[dp++] = (byte)base64[(b1 << 2) & 0x3f];
if (doPadding) {
dst[dp++] = '=';
}
}
}
return dp;
}
}
/**
* This class implements a decoder for decoding byte data using the
* Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
*
* <p> The Base64 padding character {@code '='} is accepted and
* interpreted as the end of the encoded byte data, but is not
* required. So if the final unit of the encoded byte data only has
* two or three Base64 characters (without the corresponding padding
* character(s) padded), they are decoded as if followed by padding
* character(s). If there is a padding character present in the
* final unit, the correct number of padding character(s) must be
* present, otherwise {@code IllegalArgumentException} (
* {@code IOException} when reading from a Base64 stream) is thrown
* during decoding.
*
* <p> Instances of {@link Decoder} class are safe for use by
* multiple concurrent threads.
*
* <p> Unless otherwise noted, passing a {@code null} argument to
* a method of this class will cause a
* {@link NullPointerException NullPointerException} to
* be thrown.
*
* @see Encoder
* @since 1.8
*/
public static class Decoder {
private final boolean isURL;
private final boolean isMIME;
private Decoder(boolean isURL, boolean isMIME) {
this.isURL = isURL;
this.isMIME = isMIME;
}
/**
* Lookup table for decoding unicode characters drawn from the
* "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into
* their 6-bit positive integer equivalents. Characters that
* are not in the Base64 alphabet but fall within the bounds of
* the array are encoded to -1.
*
*/
private static final int[] fromBase64 = new int[256];
static {
Arrays.fill(fromBase64, -1);
for (int i = 0; i < Encoder.toBase64.length; i++)
fromBase64[Encoder.toBase64[i]] = i;
fromBase64['='] = -2;
}
/**
* Lookup table for decoding "URL and Filename safe Base64 Alphabet"
* as specified in Table2 of the RFC 4648.
*/
private static final int[] fromBase64URL = new int[256];
static {
Arrays.fill(fromBase64URL, -1);
for (int i = 0; i < Encoder.toBase64URL.length; i++)
fromBase64URL[Encoder.toBase64URL[i]] = i;
fromBase64URL['='] = -2;
}
static final Decoder RFC4648 = new Decoder(false, false);
static final Decoder RFC4648_URLSAFE = new Decoder(true, false);
static final Decoder RFC2045 = new Decoder(false, true);
/**
* Decodes all bytes from the input byte array using the {@link AndroidOBase64}
* encoding scheme, writing the results into a newly-allocated output
* byte array. The returned byte array is of the length of the resulting
* bytes.
*
* @param src
* the byte array to decode
*
* @return A newly-allocated byte array containing the decoded bytes.
*
* @throws IllegalArgumentException
* if {@code src} is not in valid Base64 scheme
*/
public byte[] decode(byte[] src) {
byte[] dst = new byte[outLength(src, 0, src.length)];
int ret = decode0(src, 0, src.length, dst);
if (ret != dst.length) {
dst = Arrays.copyOf(dst, ret);
}
return dst;
}
/**
* Decodes a Base64 encoded String into a newly-allocated byte array
* using the {@link AndroidOBase64} encoding scheme.
*
* <p> An invocation of this method has exactly the same effect as invoking
* {@code decode(src.getBytes(StandardCharsets.ISO_8859_1))}
*
* @param src
* the string to decode
*
* @return A newly-allocated byte array containing the decoded bytes.
*
* @throws IllegalArgumentException
* if {@code src} is not in valid Base64 scheme
*/
public byte[] decode(String src) {
return decode(src.getBytes(StandardCharsets.ISO_8859_1));
}
/**
* Decodes all bytes from the input byte array using the {@link AndroidOBase64}
* encoding scheme, writing the results into the given output byte array,
* starting at offset 0.
*
* <p> It is the responsibility of the invoker of this method to make
* sure the output byte array {@code dst} has enough space for decoding
* all bytes from the input byte array. No bytes will be be written to
* the output byte array if the output byte array is not big enough.
*
* <p> If the input byte array is not in valid Base64 encoding scheme
* then some bytes may have been written to the output byte array before
* IllegalargumentException is thrown.
*
* @param src
* the byte array to decode
* @param dst
* the output byte array
*
* @return The number of bytes written to the output byte array
*
* @throws IllegalArgumentException
* if {@code src} is not in valid Base64 scheme, or {@code dst}
* does not have enough space for decoding all input bytes.
*/
public int decode(byte[] src, byte[] dst) {
int len = outLength(src, 0, src.length);
if (dst.length < len)
throw new IllegalArgumentException(
"Output byte array is too small for decoding all input bytes");
return decode0(src, 0, src.length, dst);
}
/**
* Decodes all bytes from the input byte buffer using the {@link AndroidOBase64}
* encoding scheme, writing the results into a newly-allocated ByteBuffer.
*
* <p> Upon return, the source buffer's position will be updated to
* its limit; its limit will not have been changed. The returned
* output buffer's position will be zero and its limit will be the
* number of resulting decoded bytes
*
* <p> {@code IllegalArgumentException} is thrown if the input buffer
* is not in valid Base64 encoding scheme. The position of the input
* buffer will not be advanced in this case.
*
* @param buffer
* the ByteBuffer to decode
*
* @return A newly-allocated byte buffer containing the decoded bytes
*
* @throws IllegalArgumentException
* if {@code src} is not in valid Base64 scheme.
*/
public ByteBuffer decode(ByteBuffer buffer) {
int pos0 = buffer.position();
try {
byte[] src;
int sp, sl;
if (buffer.hasArray()) {
src = buffer.array();
sp = buffer.arrayOffset() + buffer.position();
sl = buffer.arrayOffset() + buffer.limit();
buffer.position(buffer.limit());
} else {
src = new byte[buffer.remaining()];
buffer.get(src);
sp = 0;
sl = src.length;
}
byte[] dst = new byte[outLength(src, sp, sl)];
return ByteBuffer.wrap(dst, 0, decode0(src, sp, sl, dst));
} catch (IllegalArgumentException iae) {
buffer.position(pos0);
throw iae;
}
}
/**
* Returns an input stream for decoding {@link AndroidOBase64} encoded byte stream.
*
* <p> The {@code read} methods of the returned {@code InputStream} will
* throw {@code IOException} when reading bytes that cannot be decoded.
*
* <p> Closing the returned input stream will close the underlying
* input stream.
*
* @param is
* the input stream
*
* @return the input stream for decoding the specified Base64 encoded
* byte stream
*/
public InputStream wrap(InputStream is) {
Objects.requireNonNull(is);
return new DecInputStream(is, isURL ? fromBase64URL : fromBase64, isMIME);
}
private int outLength(byte[] src, int sp, int sl) {
int[] base64 = isURL ? fromBase64URL : fromBase64;
int paddings = 0;
int len = sl - sp;
if (len == 0)
return 0;
if (len < 2) {
if (isMIME && base64[0] == -1)
return 0;
throw new IllegalArgumentException(
"Input byte[] should at least have 2 bytes for base64 bytes");
}
if (isMIME) {
// scan all bytes to fill out all non-alphabet. a performance
// trade-off of pre-scan or Arrays.copyOf
int n = 0;
while (sp < sl) {
int b = src[sp++] & 0xff;
if (b == '=') {
len -= (sl - sp + 1);
break;
}
if ((b = base64[b]) == -1)
n++;
}
len -= n;
} else {
if (src[sl - 1] == '=') {
paddings++;
if (src[sl - 2] == '=')
paddings++;
}
}
if (paddings == 0 && (len & 0x3) != 0)
paddings = 4 - (len & 0x3);
return 3 * ((len + 3) / 4) - paddings;
}
private int decode0(byte[] src, int sp, int sl, byte[] dst) {
int[] base64 = isURL ? fromBase64URL : fromBase64;
int dp = 0;
int bits = 0;
int shiftto = 18; // pos of first byte of 4-byte atom
while (sp < sl) {
int b = src[sp++] & 0xff;
if ((b = base64[b]) < 0) {
if (b == -2) { // padding byte '='
// = shiftto==18 unnecessary padding
// x= shiftto==12 a dangling single x
// x to be handled together with non-padding case
// xx= shiftto==6&&sp==sl missing last =
// xx=y shiftto==6 last is not =
if (shiftto == 6 && (sp == sl || src[sp++] != '=') ||
shiftto == 18) {
throw new IllegalArgumentException(
"Input byte array has wrong 4-byte ending unit");
}
break;
}
if (isMIME) // skip if for rfc2045
continue;
else
throw new IllegalArgumentException(
"Illegal base64 character " +
Integer.toString(src[sp - 1], 16));
}
bits |= (b << shiftto);
shiftto -= 6;
if (shiftto < 0) {
dst[dp++] = (byte)(bits >> 16);
dst[dp++] = (byte)(bits >> 8);
dst[dp++] = (byte)(bits);
shiftto = 18;
bits = 0;
}
}
// reached end of byte array or hit padding '=' characters.
if (shiftto == 6) {
dst[dp++] = (byte)(bits >> 16);
} else if (shiftto == 0) {
dst[dp++] = (byte)(bits >> 16);
dst[dp++] = (byte)(bits >> 8);
} else if (shiftto == 12) {
// dangling single "x", incorrectly encoded.
throw new IllegalArgumentException(
"Last unit does not have enough valid bits");
}
// anything left is invalid, if is not MIME.
// if MIME, ignore all non-base64 character
while (sp < sl) {
if (isMIME && base64[src[sp++]] < 0)
continue;
throw new IllegalArgumentException(
"Input byte array has incorrect ending byte at " + sp);
}
return dp;
}
}
/*
* An output stream for encoding bytes into the Base64.
*/
private static class EncOutputStream extends FilterOutputStream {
private int leftover = 0;
private int b0, b1, b2;
private boolean closed = false;
private final char[] base64; // byte->base64 mapping
private final byte[] newline; // line separator, if needed
private final int linemax;
private final boolean doPadding;// whether or not to pad
private int linepos = 0;
EncOutputStream(OutputStream os, char[] base64,
byte[] newline, int linemax, boolean doPadding) {
super(os);
this.base64 = base64;
this.newline = newline;
this.linemax = linemax;
this.doPadding = doPadding;
}
@Override
public void write(int b) throws IOException {
byte[] buf = new byte[1];
buf[0] = (byte)(b & 0xff);
write(buf, 0, 1);
}
private void checkNewline() throws IOException {
if (linepos == linemax) {
out.write(newline);
linepos = 0;
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (closed)
throw new IOException("Stream is closed");
if (off < 0 || len < 0 || len > b.length - off)
throw new ArrayIndexOutOfBoundsException();
if (len == 0)
return;
if (leftover != 0) {
if (leftover == 1) {
b1 = b[off++] & 0xff;
len--;
if (len == 0) {
leftover++;
return;
}
}
b2 = b[off++] & 0xff;
len--;
checkNewline();
out.write(base64[b0 >> 2]);
out.write(base64[(b0 << 4) & 0x3f | (b1 >> 4)]);
out.write(base64[(b1 << 2) & 0x3f | (b2 >> 6)]);
out.write(base64[b2 & 0x3f]);
linepos += 4;
}
int nBits24 = len / 3;
leftover = len - (nBits24 * 3);
while (nBits24-- > 0) {
checkNewline();
int bits = (b[off++] & 0xff) << 16 |
(b[off++] & 0xff) << 8 |
(b[off++] & 0xff);
out.write(base64[(bits >>> 18) & 0x3f]);
out.write(base64[(bits >>> 12) & 0x3f]);
out.write(base64[(bits >>> 6) & 0x3f]);
out.write(base64[bits & 0x3f]);
linepos += 4;
}
if (leftover == 1) {
b0 = b[off++] & 0xff;
} else if (leftover == 2) {
b0 = b[off++] & 0xff;
b1 = b[off++] & 0xff;
}
}
@Override
public void close() throws IOException {
if (!closed) {
closed = true;
if (leftover == 1) {
checkNewline();
out.write(base64[b0 >> 2]);
out.write(base64[(b0 << 4) & 0x3f]);
if (doPadding) {
out.write('=');
out.write('=');
}
} else if (leftover == 2) {
checkNewline();
out.write(base64[b0 >> 2]);
out.write(base64[(b0 << 4) & 0x3f | (b1 >> 4)]);
out.write(base64[(b1 << 2) & 0x3f]);
if (doPadding) {
out.write('=');
}
}
leftover = 0;
out.close();
}
}
}
/*
* An input stream for decoding Base64 bytes
*/
private static class DecInputStream extends InputStream {
private final InputStream is;
private final boolean isMIME;
private final int[] base64; // base64 -> byte mapping
private int bits = 0; // 24-bit buffer for decoding
private int nextin = 18; // next available "off" in "bits" for input;
// -> 18, 12, 6, 0
private int nextout = -8; // next available "off" in "bits" for output;
// -> 8, 0, -8 (no byte for output)
private boolean eof = false;
private boolean closed = false;
DecInputStream(InputStream is, int[] base64, boolean isMIME) {
this.is = is;
this.base64 = base64;
this.isMIME = isMIME;
}
private byte[] sbBuf = new byte[1];
@Override
public int read() throws IOException {
return read(sbBuf, 0, 1) == -1 ? -1 : sbBuf[0] & 0xff;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (closed)
throw new IOException("Stream is closed");
if (eof && nextout < 0) // eof and no leftover
return -1;
if (off < 0 || len < 0 || len > b.length - off)
throw new IndexOutOfBoundsException();
int oldOff = off;
if (nextout >= 0) { // leftover output byte(s) in bits buf
do {
if (len == 0)
return off - oldOff;
b[off++] = (byte)(bits >> nextout);
len--;
nextout -= 8;
} while (nextout >= 0);
bits = 0;
}
while (len > 0) {
int v = is.read();
if (v == -1) {
eof = true;
if (nextin != 18) {
if (nextin == 12)
throw new IOException("Base64 stream has one un-decoded dangling byte.");
// treat ending xx/xxx without padding character legal.
// same logic as v == '=' below
b[off++] = (byte)(bits >> (16));
len--;
if (nextin == 0) { // only one padding byte
if (len == 0) { // no enough output space
bits >>= 8; // shift to lowest byte
nextout = 0;
} else {
b[off++] = (byte) (bits >> 8);
}
}
}
if (off == oldOff)
return -1;
else
return off - oldOff;
}
if (v == '=') { // padding byte(s)
// = shiftto==18 unnecessary padding
// x= shiftto==12 dangling x, invalid unit
// xx= shiftto==6 && missing last '='
// xx=y or last is not '='
if (nextin == 18 || nextin == 12 ||
nextin == 6 && is.read() != '=') {
throw new IOException("Illegal base64 ending sequence:" + nextin);
}
b[off++] = (byte)(bits >> (16));
len--;
if (nextin == 0) { // only one padding byte
if (len == 0) { // no enough output space
bits >>= 8; // shift to lowest byte
nextout = 0;
} else {
b[off++] = (byte) (bits >> 8);
}
}
eof = true;
break;
}
if ((v = base64[v]) == -1) {
if (isMIME) // skip if for rfc2045
continue;
else
throw new IOException("Illegal base64 character " +
Integer.toString(v, 16));
}
bits |= (v << nextin);
if (nextin == 0) {
nextin = 18; // clear for next
nextout = 16;
while (nextout >= 0) {
b[off++] = (byte)(bits >> nextout);
len--;
nextout -= 8;
if (len == 0 && nextout >= 0) { // don't clean "bits"
return off - oldOff;
}
}
bits = 0;
} else {
nextin -= 6;
}
}
return off - oldOff;
}
@Override
public int available() throws IOException {
if (closed)
throw new IOException("Stream is closed");
return is.available(); // TBD:
}
@Override
public void close() throws IOException {
if (!closed) {
closed = true;
is.close();
}
}
}
}
package com.gem.media.splash.base.crash;
import android.content.Context;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import java.util.Locale;
public final class CountryUtil {
private static final String TAG = "CountryUtil";
CountryUtil() {
}
public static String getCountryCode(Context context) {
String countryCode = "";
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
if (telephonyManager != null) {
countryCode = telephonyManager.getSimCountryIso();
if (countryCode != null && countryCode.length() == 2) {
return countryCode.toUpperCase(Locale.US);
}
if (telephonyManager.getPhoneType() != 2) {
countryCode = telephonyManager.getNetworkCountryIso();
if (countryCode != null && countryCode.length() == 2) {
return countryCode.toUpperCase(Locale.US);
}
}
}
} catch (Exception e) {
}
return countryCode;
}
public static String getSimCountryIso(Context context) {
String countryCode = "";
try {
countryCode = ((TelephonyManager) context.getSystemService("phone")).getSimCountryIso();
if (countryCode != null && countryCode.length() == 2) {
return countryCode.toUpperCase(Locale.US);
}
} catch (Exception e) {
}
return countryCode;
}
public static String getNetworkCountryIso(Context context) {
String countryCode = "";
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
if (telephonyManager.getPhoneType() != 2) {
countryCode = telephonyManager.getNetworkCountryIso();
if (countryCode != null && countryCode.length() == 2) {
return countryCode.toUpperCase(Locale.US);
}
}
} catch (Exception e) {
}
return countryCode;
}
public static String getLocalCountry(Context context) {
String countryCode = "";
try {
if (Build.VERSION.SDK_INT >= 24) {
countryCode = context.getResources().getConfiguration().getLocales().get(0).getCountry();
} else {
countryCode = context.getResources().getConfiguration().locale.getCountry();
}
} catch (Exception e) {
}
return countryCode;
}
public static String getSimOperatorMcc(Context context) {
try {
String operator = ((TelephonyManager) context.getApplicationContext().getSystemService("phone")).getSimOperator();
if (TextUtils.isEmpty(operator)) {
return "";
}
return operator.substring(0, 3);
} catch (Exception e) {
return "";
}
}
}
package com.gem.media.splash.base.crash;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.util.Log;
import com.gem.media.splash.base.utils.ALog;
import com.or.ange.dot.utils.ThreadManager;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static final String TAG = "CrashHandler";
private static final String DEX_EX = "dx_crs_ex";
private Thread.UncaughtExceptionHandler defUncaughtExceptionHandler;
private volatile boolean isInit = false;
private String appId;
private String appVersionName;
private String appVersionCode;
private String reportUrl;
private final CrashReportRunnable carshReportRunnable;
private static class Holder {
private static final CrashHandler INSTANCE = new CrashHandler();
}
private CrashHandler() {
carshReportRunnable = new CrashReportRunnable();
}
public static CrashHandler getInstance() {
return Holder.INSTANCE;
}
public void setup(Context context, String url, String appId) {
if (isInit) {
return;
}
isInit = true;
this.appId = appId;
appVersionName = getAppVersionName(context);
appVersionCode = getAppVersionCode(context);
this.reportUrl = url;
try {
defUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
} catch (Exception e) {
//
}
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
String exception = Log.getStackTraceString(throwable);
ALog.d(TAG, "exception---" + exception);
Map<String, String> map = new HashMap<>();
map.put("ex", exception);
Event event = generateEvent(DEX_EX, map);
carshReportRunnable.setEvent(event);
carshReportRunnable.setAppId(appId);
carshReportRunnable.setUrl(reportUrl);
ThreadManager.getNormalExecutor().submit(carshReportRunnable);
// defUncaughtExceptionHandler.uncaughtException(thread, throwable);
}
private Event generateEvent(String eventId, Map<String, String> params) {
Event event = new Event();
event.setEventId(eventId);
event.setVersionName(appVersionName);
event.setVersionCode(appVersionCode);
event.setTimestamp(System.currentTimeMillis());
if (params != null) {
event.setParams(new JSONObject(params).toString());
}
return event;
}
private static String getAppVersionName(Context context2) {
try {
PackageInfo pi = context2.getPackageManager().getPackageInfo(context2.getPackageName(), 0);
if (pi != null) {
return pi.versionName;
}
return "error:version";
} catch (Exception e) {
e.printStackTrace();
return "error:version";
}
}
private static String getAppVersionCode(Context context2) {
try {
PackageInfo pi = context2.getPackageManager().getPackageInfo(context2.getPackageName(), 0);
if (pi != null) {
return String.valueOf(pi.versionCode);
}
return "-1";
} catch (Exception e) {
e.printStackTrace();
return "-1";
}
}
}
package com.gem.media.splash.base.crash;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Process;
import android.text.TextUtils;
import com.ads.cal.notes.BaseApplication;
import com.or.ange.dot.SystemUtils;
import com.or.ange.dot.utils.DeviceIDUtils;
import com.or.ange.dot.utils.LLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
public class CrashReportRunnable implements Runnable {
private static final String TAG = "ReportRunnable";
private JSONObject common;
private String imei;
private String androidId;
private String appId;
private String country;
private String language;
private String countryCode;
private String simOperatorMcc;
private volatile boolean isReporting = false;
private String reportUrl;
private Event event;
public CrashReportRunnable() {
Context context = BaseApplication.getApplication();
try {
this.imei = DeviceIDUtils.getImei(context);
this.androidId = SystemUtils.getAndroidId(context);
this.country = Locale.getDefault().getCountry();
this.language = Locale.getDefault().getLanguage();
} catch (Exception e2) {
}
try {
this.countryCode = CountryUtil.getCountryCode(context);
this.simOperatorMcc = CountryUtil.getSimOperatorMcc(context);
} catch (Exception e3) {
}
}
public void setEvent(Event event) {
this.event = event;
}
public void setUrl(String reportUrl) {
this.reportUrl = reportUrl;
}
public void setAppId(String appId) {
this.appId = appId;
}
@Override
public void run() {
List<Event> events = new ArrayList<>();
if (event != null) {
events.add(event);
}
if (events.isEmpty()) {
LLog.d(TAG, "events is empty, not report.");
return;
}
boolean success = false;
this.isReporting = true;
BufferedReader br = null;
try {
JSONObject object = getTrackerJSONObject(events);
HashMap<String, String> heads = new HashMap<>();
heads.put("Content-Type", "application/json");
HttpURLConnection conn = Http.post(reportUrl, heads, null, object.toString());
if (conn != null) {
success = conn.getResponseCode() == 200;
if (success) {
StringBuilder rest = new StringBuilder();
br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
while (true) {
String line = br.readLine();
if (null == line) {
break;
}
rest.append(line);
}
success = new JSONObject(AESEncryptUtil.decrypt2(rest.toString())).optInt("a") == 0;
}
}
if (br != null) {
try {
br.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (success) {
LLog.d(TAG, "track after success ");
} else {
if (conn == null) {
LLog.d(TAG, "track fail. null" );
} else {
LLog.d(TAG, "track fail. code = " + conn.getResponseCode());
}
}
this.isReporting = false;
} catch (Exception e) {
if (br != null) {
try {
br.close();
} catch (Exception e22) {
this.isReporting = false;
}
}
if (!success) {
}
this.isReporting = false;
} catch (Throwable th) {
if (br != null) {
try {
br.close();
} catch (Exception e23) {
e23.printStackTrace();
throw th;
}
}
if (!success) {
}
this.isReporting = false;
throw th;
} finally {
LLog.d(TAG, " Process.killProcess "+Process.myPid());
Process.killProcess(Process.myPid());
}
}
private JSONObject getTrackerJSONObject(List<Event> events) {
JSONObject object = new JSONObject();
try {
object.put("cp", getCommonJSONObject());
JSONArray array = new JSONArray();
for (Event event : events) {
array.put(getEventJSONObject(event));
}
object.put("e", array);
object.put("n", "1");
} catch (JSONException e) {
LLog.d(TAG, e.toString());
}
return object;
}
@SuppressLint({"MissingPermission"})
private JSONObject getCommonJSONObject() throws JSONException {
Context context = BaseApplication.getApplication();
if (this.common == null && null != context) {
String pkgName = context.getPackageName();
this.common = new JSONObject();
this.common.put("ai", this.appId);
this.common.put("i", this.imei);
this.common.put("a_id", this.androidId);
this.common.put("pk", pkgName);
this.common.put("vc", getAppVersionCode());
this.common.put("vn", getAppVersionName());
this.common.put("ol", Build.VERSION.SDK_INT);
this.common.put("ov", Build.VERSION.RELEASE);
this.common.put("b", Build.BRAND);
this.common.put("m", Build.MODEL);
this.common.put("d", Build.DEVICE);
this.common.put("bo", Build.BOARD);
this.common.put("ft", Build.FINGERPRINT);
this.common.put("hw", Build.HARDWARE);
this.common.put("dy", Build.DISPLAY);
this.common.put("id", Build.ID);
this.common.put("pt", Build.PRODUCT);
this.common.put("us", Build.USER);
this.common.put("mf", Build.MANUFACTURER);
this.common.put("cn", this.country);
this.common.put("lag", this.language);
this.common.put("coc", this.countryCode);
this.common.put("som", this.simOperatorMcc);
if (Build.VERSION.SDK_INT >= 26) {
String serial = "";
try {
serial = Build.getSerial();
} catch (Exception e) {
}
this.common.put("sn", serial);
}
}
return this.common;
}
private JSONObject getEventJSONObject(Event event) throws JSONException {
JSONObject object = new JSONObject();
object.put("ei", event.getEventId());
if (!BaseApplication.getApplication().getPackageName().equals(event.getLabel())) {
object.put("label", event.getLabel());
}
object.put("et", event.getTimestamp());
if (!getAppVersionName().equals(event.getVersionName())) {
object.put("vc", event.getVersionCode());
object.put("vn", event.getVersionName());
}
if (!TextUtils.isEmpty(event.getParams())) {
object.put("pm", new JSONObject(event.getParams()));
}
return object;
}
public boolean isReporting() {
return this.isReporting;
}
private static String getAppVersionName() {
try {
Context context = BaseApplication.getApplication();
PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
if (pi != null) {
return pi.versionName;
}
return "error:version";
} catch (Exception e) {
e.printStackTrace();
return "error:version";
}
}
private String getAppVersionCode() {
try {
Context context = BaseApplication.getApplication();
PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
if (pi != null) {
return String.valueOf(pi.versionCode);
}
return "-1";
} catch (Exception e) {
e.printStackTrace();
return "-1";
}
}
}
package com.gem.media.splash.base.crash;
public class Event {
private int id;
private String eventId;
private String label;
private String versionName;
private String versionCode;
private long timestamp;
private String params;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getEventId() {
return this.eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
public String getLabel() {
return this.label;
}
public void setLabel(String label) {
this.label = label;
}
public String getVersionName() {
return this.versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public String getVersionCode() {
return this.versionCode;
}
public void setVersionCode(String versionCode) {
this.versionCode = versionCode;
}
public long getTimestamp() {
return this.timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getParams() {
return this.params;
}
public void setParams(String params) {
this.params = params;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Event event = (Event) o;
if (this.timestamp != event.timestamp) {
return false;
}
return this.eventId.equals(event.eventId);
}
public int hashCode() {
return (31 * this.eventId.hashCode()) + ((int) (this.timestamp ^ (this.timestamp >>> 32)));
}
public String toString() {
return "Event(id='" + this.id + "', eventId='" + this.eventId + "', label='" + this.label + "', vn='" + this.versionName + "', vc='" + this.versionCode + "', params='" + this.params + "')";
}
}
package com.gem.media.splash.base.crash;
import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Base64;
import com.or.ange.dot.utils.LLog;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Http {
private static final String TAG = "DotHttp";
private Http() {
throw new UnsupportedOperationException();
}
private static void setHttpsFactory(HttpURLConnection conn) {
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection httpsConn = (HttpsURLConnection)conn;
httpsConn.setHostnameVerifier(new SkipHostnameVerifier());
try {
httpsConn.setSSLSocketFactory(createSslSocketFactory());
} catch (Exception var3) {
var3.printStackTrace();
}
}
}
public static HttpURLConnection post(String uri, Map<String, String> heads, Map<String, String> params, String body) throws IOException {
URL url;
if (params != null && params.size() > 0) {
url = new URL(uri + "?" + convertRequestParamsToString(params));
} else {
url = new URL(uri);
}
OutputStream outputStream = null;
while(true) {
try {
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(20000);
conn.setReadTimeout(20000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("e", "5");
setHttpsFactory(conn);
if (!TextUtils.isEmpty(body)) {
String encryptBody = Base64.encodeToString(AESEncryptUtil.encrypt2(body), Base64.NO_WRAP);
outputStream = conn.getOutputStream();
outputStream.write((encryptBody).getBytes("UTF-8"));
outputStream.flush();
}
int responseCode = conn.getResponseCode();
LLog.d(TAG, "responseCode "+responseCode);
switch (responseCode) {
case 200:
case 206:
HttpURLConnection var25 = conn;
return var25;
case 301:
case 302:
case 303:
case 307:
String location = conn.getHeaderField("Location");
url = new URL(location);
break;
case 416:
throw new StopRequestException(416);
default:
return null;
}
} catch (Exception var21) {
return null;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException var20) {
}
}
}
}
}
public static String convertRequestParamsToString(Map<String, String> params) throws IOException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (String key : params.keySet()) {
String value = params.get(key);
if (!TextUtils.isEmpty(value)) {
if (first) {
first = false;
} else {
result.append("&");
}
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value, "UTF-8"));
}
}
return result.toString();
}
private static SSLSocketFactory createSslSocketFactory() throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{new SkipX509TrustManager()}, new SecureRandom());
return context.getSocketFactory();
}
public static class StopRequestException extends RuntimeException {
private final int code;
public StopRequestException(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
}
private static class SkipHostnameVerifier implements HostnameVerifier {
private SkipHostnameVerifier() {
}
@SuppressLint({"BadHostnameVerifier"})
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
private static class SkipX509TrustManager implements X509TrustManager {
private SkipX509TrustManager() {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@SuppressLint({"TrustAllX509TrustManager"})
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@SuppressLint({"TrustAllX509TrustManager"})
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}
}
/*
* Tencent is pleased to support the open source community by making wechat-matrix available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gem.media.splash.base.matrix;
public enum MatrixEnum {
/*****matrix begin********/
// trace
clicfg_matrix_trace_fps_enable,
clicfg_matrix_trace_care_scene_set,
clicfg_matrix_trace_fps_time_slice,
clicfg_matrix_trace_load_activity_threshold,
clicfg_matrix_trace_evil_method_threshold,
clicfg_matrix_trace_fps_report_threshold,
clicfg_matrix_trace_max_evil_method_stack_num,
clicfg_matrix_trace_max_evil_method_try_trim_num,
clicfg_matrix_trace_min_evil_method_druration,
clicfg_matrix_trace_time_upload_duration,
clicfg_matrix_fps_dropped_normal,
clicfg_matrix_fps_dropped_middle,
clicfg_matrix_fps_dropped_high,
clicfg_matrix_fps_dropped_frozen,
clicfg_matrix_trace_evil_method_enable,
clicfg_matrix_trace_startup_enable,
clicfg_matrix_trace_app_start_up_threshold,
clicfg_matrix_trace_fps_frame_fresh_threshold,
clicfg_matrix_trace_min_evil_method_run_cnt,
clicfg_matrix_trace_min_evil_method_dur_time,
clicfg_matrix_trace_splash_activity_name,
//io
clicfg_matrix_io_file_io_main_thread_enable,
clicfg_matrix_io_main_thread_enable_threshold,
clicfg_matrix_io_small_buffer_enable,
clicfg_matrix_io_small_buffer_threshold,
clicfg_matrix_io_small_buffer_operator_times,
clicfg_matrix_io_repeated_read_enable,
clicfg_matrix_io_repeated_read_threshold,
clicfg_matrix_io_closeable_leak_enable,
//resource
clicfg_matrix_resource_detect_interval_millis,
clicfg_matrix_resource_max_detect_times,
clicfg_matrix_resource_dump_hprof_enable,
/******matrix end*******/
}
package com.gem.media.splash.base.matrix;
import android.app.Application;
import android.util.Log;
import com.gem.media.splash.base.utils.ALog;
import com.tencent.matrix.Matrix;
import com.tencent.matrix.trace.TracePlugin;
import com.tencent.matrix.trace.config.TraceConfig;
public class MatrixUtils {
private static final String TAG = "MatrixUtils";
public static void init(Application application) {
try {
MdDynamicConfigImpl dynamicConfig = new MdDynamicConfigImpl();
ALog.d(TAG, "Start Matrix configurations start ");
// Builder. Not necessary while some plugins can be configured separately.
Matrix.Builder builder = new Matrix.Builder(application);
builder.pluginListener(new MdPluginListener(application));
TracePlugin tracePlugin = configureTracePlugin(dynamicConfig);
builder.plugin(tracePlugin);
Matrix.init(builder.build());
tracePlugin.start();
ALog.d(TAG, "Start Matrix configurations end ");
} catch (Exception e) {
ALog.e(TAG, "matrix init e :" + Log.getStackTraceString(e));
}
}
private static TracePlugin configureTracePlugin(MdDynamicConfigImpl dynamicConfig) {
boolean fpsEnable = dynamicConfig.isFPSEnable();
boolean traceEnable = dynamicConfig.isTraceEnable();
boolean signalAnrTraceEnable = dynamicConfig.isSignalAnrTraceEnable();
ALog.d(TAG, "fpsEnable :" + fpsEnable + ",,traceEnable :" + traceEnable
+ ", signalAnrTraceEnable :" + signalAnrTraceEnable);
TraceConfig traceConfig = new TraceConfig.Builder()
.dynamicConfig(dynamicConfig)
.enableAnrTrace(traceEnable)
.enableSignalAnrTrace(signalAnrTraceEnable) // Introduced in Matrix 2.0
.enableEvilMethodTrace(false)
.isDebug(false)
.isDevEnv(false)
.build();
return new TracePlugin(traceConfig);
}
}
/*
* Tencent is pleased to support the open source community by making wechat-matrix available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gem.media.splash.base.matrix;
import com.tencent.mrs.plugin.IDynamicConfig;
public class MdDynamicConfigImpl implements IDynamicConfig {
private static final String TAG = "Matrix.MdDynamicConfigImpl";
public MdDynamicConfigImpl() {
}
public boolean isFPSEnable() {
return false;
}
public boolean isTraceEnable() {
return true;
}
public boolean isSignalAnrTraceEnable() {
return true;
}
public boolean isMatrixEnable() {
return true;
}
@Override
public String get(String key, String defStr) {
return defStr;
}
@Override
public int get(String key, int defInt) {
//TODO here return default value which is inside sdk, you can change it as you wish. matrix-sdk-key in class MatrixEnum.
if (MatrixEnum.clicfg_matrix_trace_fps_report_threshold.name().equals(key)) {
return 10000;
}
if (MatrixEnum.clicfg_matrix_trace_fps_time_slice.name().equals(key)) {
return 12000;
}
return defInt;
}
@Override
public long get(String key, long defLong) {
//TODO here return default value which is inside sdk, you can change it as you wish. matrix-sdk-key in class MatrixEnum.
if (MatrixEnum.clicfg_matrix_trace_fps_report_threshold.name().equals(key)) {
return 10000L;
}
return defLong;
}
@Override
public boolean get(String key, boolean defBool) {
//TODO here return default value which is inside sdk, you can change it as you wish. matrix-sdk-key in class MatrixEnum.
return defBool;
}
@Override
public float get(String key, float defFloat) {
//TODO here return default value which is inside sdk, you can change it as you wish. matrix-sdk-key in class MatrixEnum.
return defFloat;
}
}
/*
* Tencent is pleased to support the open source community by making wechat-matrix available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gem.media.splash.base.matrix;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import com.gem.media.StatsStaticHelper;
import com.gem.media.splash.base.utils.ALog;
import com.tencent.matrix.plugin.DefaultPluginListener;
import com.tencent.matrix.report.Issue;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MdPluginListener extends DefaultPluginListener {
public static final String TAG = "MdPluginListener";
private static final String EVENT_ANR_EXCEPTION = "anr_ex";
private static final int MSG_CHECK_REAL_ANR = 1;
private static final int CHECK_ERROR_STATE_INTERVAL = 500;
private static final int ANR_DUMP_MAX_TIME = 20000;
private static final int CHECK_ERROR_STATE_COUNT = ANR_DUMP_MAX_TIME / CHECK_ERROR_STATE_INTERVAL;
private Context context;
private Handler anrCheckHandler;
private HandlerThread handlerThread;
private volatile int checkNum = 0;
public MdPluginListener(Context context) {
super(context);
this.context = context;
}
private void initHandle() {
handlerThread = new HandlerThread("mtx_ar_t");
handlerThread.start();
anrCheckHandler = new Handler(handlerThread.getLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case MSG_CHECK_REAL_ANR:
try {
boolean myAnr = checkErrorState();
// ALog.d(TAG, " myAnr :" + myAnr + ", checkNum :" + checkNum);
if (myAnr) {
ALog.d(TAG, "real anr occur !");
Process.killProcess(Process.myPid());
break;
}
ALog.d(TAG, " ---not anr ----" + ", checkNum :" + checkNum);
} catch (Throwable e) {
ALog.e(TAG, "myAnr e : " + Log.getStackTraceString(e));
} finally {
checkNum++;
ALog.d(TAG, "finally checkNum: " + checkNum + ",,max :" + CHECK_ERROR_STATE_COUNT);
if (checkNum < CHECK_ERROR_STATE_COUNT && anrCheckHandler != null) {
try {
Message message = Message.obtain();
message.what = MSG_CHECK_REAL_ANR;
message.arg1 = checkNum;
anrCheckHandler.sendMessageDelayed(message, CHECK_ERROR_STATE_INTERVAL);
} catch (Exception e) {
destroyHandler();
}
} else {
ALog.d(TAG, "destroyHandler");
destroyHandler();
}
}
break;
}
}
};
}
private void destroyHandler() {
try {
if (handlerThread != null) {
handlerThread.quitSafely();
}
} catch (Exception e) {
}
handlerThread = null;
anrCheckHandler = null;
checkNum = 0;
}
@Override
public void onReportIssue(final Issue issue) {
super.onReportIssue(issue);
// ALog.d(TAG, " issue :" + issue);
checkANRHappened(issue);
}
private void checkANRHappened(Issue issue) {
if (issue == null) {
return;
}
try {
JSONObject content = issue.getContent();
if (content == null) {
return;
}
String type = content.getString("detail");
ALog.d(TAG, " issue type :" + type);
if (!TextUtils.isEmpty(type) && type.contains("ANR")) {
ALog.d(TAG, "check anr !");
statAnr(type);
if (anrCheckHandler == null) {
initHandle();
}
Message message = Message.obtain();
message.what = MSG_CHECK_REAL_ANR;
message.arg1 = checkNum;
anrCheckHandler.sendMessageDelayed(message, CHECK_ERROR_STATE_INTERVAL);
}
} catch (Exception e) {
}
// ALog.d(TAG, " isAnrMsg :" + isAnrMsg);
/* if (!isAnrMsg) {
return;
}*/
/* new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 40; i++) {
try {
boolean myAnr = checkErrorState();
ALog.d(TAG, " myAnr :" + myAnr + ", i :" + i);
if (myAnr) {
Process.killProcess(Process.myPid());
break;
}
ALog.d(TAG, " -------" + ", i :" + i);
Thread.sleep(500);
} catch (Throwable e) {
ALog.e(TAG, "myAnr e : " + Log.getStackTraceString(e));
break;
}
}
}
}).start();*/
}
private boolean checkErrorState() {
try {
ALog.i(TAG, "[checkErrorState] start");
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.ProcessErrorStateInfo> procs = am.getProcessesInErrorState();
if (procs == null) {
ALog.i(TAG, "[checkErrorState] procs == null");
return false;
}
for (ActivityManager.ProcessErrorStateInfo proc : procs) {
ALog.i(TAG, "[checkErrorState] found Error State proccessName = "+ proc.processName + ", proc.condition = " + proc.condition);
if (proc.uid != Process.myUid()
&& proc.condition == ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING) {
ALog.i(TAG, "maybe received other apps ANR signal");
return false;
}
if (proc.pid != Process.myPid()) continue;
if (proc.condition != ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING) {
continue;
}
ALog.i(TAG, "error sate proc.condition =" + proc.condition);
return true;
}
return false;
} catch (Throwable t) {
ALog.e(TAG, "[checkErrorState] error : %s", t.getMessage());
}
return false;
}
private void statAnr(String type) {
try {
Map<String, String> map = new HashMap<>();
map.put("type", type);
StatsStaticHelper.reportOnEvent(EVENT_ANR_EXCEPTION, null, map);
} catch (Exception e) {
}
}
}
......@@ -6,15 +6,10 @@ public class Constants {
public static final String NODE_REQUEST_SUCCESS_EID = "ad_req_dur_eid"; // 广告请求成功
public static final String NODE_SHOW_EID = "ad_exp_eid"; // 广告展示
public static final String NODE_CLICK_EID = "ad_clk_eid"; // 广告点击
public static final String NODE_OPEN_EID = "ad_open_eid"; // 广告点击
public static final String NODE_CLOSE_EID = "ad_close_eid"; // 广告关闭
public static final String NODE_ERROR_EID = "ad_faile_eid"; //广告错误
public static final String NODE_NEXT_MEDIA_AD_REQ = "next_media_ad_req"; //admob全屏广告显示错误
public static final String NODE_FAILED_TO_SHOW_EID = "ad_failed_to_show_eid"; //admob全屏广告显示错误
public static final String NODE_FAILED_TO_SHOW = "ad_failed_to_show"; //admob全屏广告显示错误
public static final String NODE_CLEAR_PAGE_SHOW = "cleanHomePageShow";
public static final String NODE_CLEAR_PAGE_SHOW_TIME = "CleanPageTime";
public static final String NODE_OPEN_EID = "ad_open_eid"; // 广告点击
public static final String NODE_OPEN = "ad_open"; // 广告
public static final String NODE_REQUEST = "ad_req"; // 广告请求
......@@ -26,14 +21,21 @@ public class Constants {
public static final String NODE_CLICK = "ad_clk"; // 广告点击
public static final String NODE_CLOSE = "ad_close"; // 广告关闭
public static final String NODE_ERROR = "ad_faile"; //广告错误
public static final String NODE_OPEN = "ad_open"; // 广告
public static final String NODE_CACHE = "ad_has_cache";//广告有缓存
public static final String NODE_CACHE_D = "ad_has_cache_d";//广告有缓存
public static final String NODE_FAILED_TO_SHOW = "ad_failed_to_show"; //admob全屏广告显示错误
public static final String NODE_NEXT_MEDIA_AD_REQ = "next_media_ad_req"; //admob全屏广告显示错误
public static final String NODE_PAGE_SHOW = "PAGE_SHOW";
public static final String NODE_AD_REQ_NET = "ad_req_net";//请求广告有网络
public static final String NODE_AD_NOT_INIT = "ad_not_init";//广告未初始化
public static final String NODE_AD_REQ_NOT_NET = "ad_req_n_net";//请求广告无网络
public static final String NODE_AD_REQ_STATUS = "ad_req_status";//广告去请求状态
public static final String MEDIA_APP_START = "media_start";
public static final String NODE_CLEAR_PAGE_SHOW = "cleanHomePageShow";
public static final String NODE_CLEAR_PAGE_RESULT_SHOW = "CLEAR_PAGE_RESULT_SHOW";
public static final String NODE_CLEAR_PAGE_SHOW_TIME = "CleanPageTime";
public static final String NODE_CLEAR_PAGE_SHOW_FAIL = "CLEAR_PAGE_SHOW_FAIL";
public static final String NODE_INTERSTITIAL_AD_VIDEO_START = "INTERSTITIAL_AD_VIDEO_START";
......@@ -43,7 +45,6 @@ public class Constants {
public static final String NODE_INTERSTITIAL_AD_VIDEO_ERROR = "INTERSTITIAL_AD_VIDEO_ERROR";
public static final String NODE_NATIVE_AD_VIDEO_START = "NATIVE_AD_VIDEO_START";
public static final String NODE_NATIVE_AD_VIDEO_END = "NATIVE_AD_VIDEO_END";
......@@ -54,30 +55,25 @@ public class Constants {
public static final String PROCESS_RESTART_AD_REQ_CALLBACK = "p_r_c";//媒体app去请求广告后APP重启事件
//H5页面展示时常参数是t
public static final String H_SHOW_TIME = "h_time";
//H5页面开始加载参数是url
public static final String H_PAGE_START = "h_p_s";
//H5页面加载完成参数是url
public static final String H_PAGE_FINISH = "h_p_f";
//H5页面加载失败参数是url 和 r
public static final String H_PAGE_ERROR = "h_p_e";
//H5页面搜索关键字参数是text
public static final String H_PAGE_SEARCH_TEXT = "h_p_st";
public static final String H_CREATE = "h_c";
public static final String N_RELOAD = "n_reload";//启动原生广告页面没有广告缓存重新加载
public static final String N_REMOVE = "n_r";//
public static final String N_CREATE = "n_c";//去启动原生广告页面
public static final String N_WM_NOT_PER = "wm_not_per_n";
public static final String N_WM_PER = "wm_per_n";
public static final String WM_NOT_PER = "wm_not_per";
public static final String WM_PER = "wm_per";
public static final String SCENARIO_1 = "chapin";
public static final String SCENARIO_2 = "yuansheng";
public static final String SCENARIO_3 = "kaipin";
public static final String SCENARIO_4 = "admob_chapin";
public static final String MEDIA_APP_START = "media_start";
public static final String START_GP_LIVE = "startGpLive";
public static final String AD_INIT_S = "m_init_s";
public static final String AD_INIT_F = "m_init_f";
public static final String START_LIVE = "startLive";
public static final String PARAM_ADID = "adId";
public static final String PARAM_PID = "pid";
public static final String PARAM_TYPE = "type";
public static final String PARAM_AD_TYPE = "ad_type";
......
......@@ -7,6 +7,7 @@ import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.view.WindowManager;
......@@ -14,8 +15,15 @@ import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
public class BarUtils {
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/09/23
* desc : utils about bar
* </pre>
*/
public final class BarUtils {
///////////////////////////////////////////////////////////////////////////
// status bar
......@@ -40,36 +48,6 @@ public class BarUtils {
return resources.getDimensionPixelSize(resourceId);
}
/**
* Set the status bar's visibility.
*
* @param activity The activity.
* @param isVisible True to set status bar visible, false otherwise.
*/
public static void setStatusBarVisibility(@NonNull final Activity activity,
final boolean isVisible) {
setStatusBarVisibility(activity.getWindow(), isVisible);
}
/**
* Set the status bar's visibility.
*
* @param window The window.
* @param isVisible True to set status bar visible, false otherwise.
*/
public static void setStatusBarVisibility(@NonNull final Window window,
final boolean isVisible) {
if (isVisible) {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
showStatusBarView(window);
addMarginTopEqualStatusBarHeight(window);
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
hideStatusBarView(window);
subtractMarginTopEqualStatusBarHeight(window);
}
}
/**
* Return whether the status bar is visible.
*
......@@ -147,7 +125,7 @@ public class BarUtils {
view.setTag(TAG_OFFSET);
Object haveSetOffset = view.getTag(KEY_OFFSET);
if (haveSetOffset != null && (Boolean) haveSetOffset) return;
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
layoutParams.setMargins(layoutParams.leftMargin,
layoutParams.topMargin + getStatusBarHeight(),
layoutParams.rightMargin,
......@@ -164,7 +142,7 @@ public class BarUtils {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
Object haveSetOffset = view.getTag(KEY_OFFSET);
if (haveSetOffset == null || !(Boolean) haveSetOffset) return;
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
layoutParams.setMargins(layoutParams.leftMargin,
layoutParams.topMargin - getStatusBarHeight(),
layoutParams.rightMargin,
......@@ -186,32 +164,6 @@ public class BarUtils {
subtractMarginTopEqualStatusBarHeight(withTag);
}
/**
* Set the status bar's color.
*
* @param activity The activity.
* @param color The status bar's color.
*/
public static View setStatusBarColor(@NonNull final Activity activity,
@ColorInt final int color) {
return setStatusBarColor(activity, color, false);
}
/**
* Set the status bar's color.
*
* @param activity The activity.
* @param color The status bar's color.
* @param isDecor True to add fake status bar in DecorView,
* false to add fake status bar in ContentView.
*/
public static View setStatusBarColor(@NonNull final Activity activity,
@ColorInt final int color,
final boolean isDecor) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return null;
transparentStatusBar(activity);
return applyStatusBarColor(activity, color, isDecor);
}
/**
......@@ -314,10 +266,6 @@ public class BarUtils {
}
}
///////////////////////////////////////////////////////////////////////////
// action bar
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// navigation bar
......@@ -385,7 +333,6 @@ public class BarUtils {
}
/**
* Set the nav bar's light mode.
*
......@@ -447,7 +394,7 @@ public class BarUtils {
}
public static void transparentNavBar(@NonNull final Window window) {
if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) return;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
window.setNavigationBarContrastEnforced(false);
}
......@@ -463,5 +410,4 @@ public class BarUtils {
int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(vis | option);
}
}
}
\ No newline at end of file
package com.gem.media.util;
import static android.media.AudioManager.AUDIOFOCUS_REQUEST_FAILED;
import android.content.Context;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import com.gem.media.splash.base.utils.ALog;
public class CAudioManagerUtils {
private static final String TAG = "CAudioManagerUtils";
private static final class CAudioManagerUtilsHolder {
private static final CAudioManagerUtils manager = new CAudioManagerUtils();
}
public static CAudioManagerUtils getInstance() {
return CAudioManagerUtilsHolder.manager;
}
private AudioManager mAudioManager;
public AudioManager getAudioManager(Context context) {
if (mAudioManager == null) {
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
return mAudioManager;
}
private boolean isInCalling(Context context) {
int mode = getAudioManager(context).getMode();
return mode == AudioManager.MODE_IN_CALL || mode == AudioManager.MODE_IN_COMMUNICATION;
}
public boolean isCalling(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int callState = telephonyManager.getCallState();
return callState != TelephonyManager.CALL_STATE_IDLE || isInCalling(context);
}
private final AudioManager.OnAudioFocusChangeListener afChangeListener = focusChange -> {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
ALog.e(TAG, "AudioManager.AUDIOFOCUS_LOSS = ");
// 长时间失去焦点,应当停止播放并释放资源
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
ALog.e(TAG, "AudioManager.AUDIOFOCUS_LOSS_TRANSIENT = ");
// 短暂失去焦点,暂停播放等待焦点恢复
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
ALog.e(TAG, "AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK = ");
// 短暂失去焦点,可降低音量继续播放(“鸭子式”处理)
break;
case AudioManager.AUDIOFOCUS_GAIN:
ALog.e(TAG, "AudioManager.AUDIOFOCUS_GAIN = ");
// 获得焦点,恢复播放
break;
}
};
private AudioFocusRequest audioFocusRequest;
public boolean isRequestAudioFocus(Context context) {
boolean b = isCalling(context);
ALog.e(TAG, "iscalling = " + b);
if (b) {
return true;
}
int result;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioFocusRequest.Builder builder = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN);
builder.setOnAudioFocusChangeListener(afChangeListener);
audioFocusRequest = builder.build();
result = getAudioManager(context).requestAudioFocus(audioFocusRequest);
} else {
result = getAudioManager(context).requestAudioFocus(afChangeListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
}
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
ALog.e(TAG, "获得音频焦点");
} else if (result == AUDIOFOCUS_REQUEST_FAILED) {
ALog.e(TAG, "没有获得音频焦点");
} else {
ALog.e(TAG, "result " + result);
}
return false;
}
public void cancelAudioFocus(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (null != audioFocusRequest) {
getAudioManager(context).abandonAudioFocusRequest(audioFocusRequest);
audioFocusRequest= null;
mAudioManager = null;
ALog.e(TAG, "abandonAudioFocusRequest");
}
} else {
getAudioManager(context).abandonAudioFocus(afChangeListener);
ALog.e(TAG, "abandonAudioFocus");
}
}
}
package com.gem.media.util;
import com.gem.media.RestartAndOnlineTimeStaticsHelper;
public class GKpLiveHelper {
private static final class KpLiveHelperHolder {
private static final GKpLiveHelper kpLiveUtil = new GKpLiveHelper();
}
public static GKpLiveHelper getInstance() {
return KpLiveHelperHolder.kpLiveUtil;
}
private long initTime = 0L;
public void init() {
if (initTime == 0L) {
initTime = System.currentTimeMillis();
} else {
long currentTime = System.currentTimeMillis();
int minute = (int) ((currentTime - initTime) / 60);
initTime = currentTime;
RestartAndOnlineTimeStaticsHelper.checkOnLineTime(minute);
}
}
}
package com.gem.media.util;
import static android.content.Context.WINDOW_SERVICE;
import android.app.KeyguardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import com.ads.cal.notes.BaseApplication;
import com.gem.media.InitA;
import com.gem.media.StatsStaticHelper;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.splash.base.utils.PkgUtils;
import java.util.HashMap;
import java.util.Map;
public class SplashWindowViewManger {
private static final String TAG = "SplashWindowViewManger";
private HandlerThread asyncHandlerThread;
private Handler asyncHandler;
private static final String ASYNC_THREAD_1 = "async_thread_1";
private HandlerThread getAsyncHandlerThread() {
if (null == asyncHandlerThread) {
asyncHandlerThread = new HandlerThread(ASYNC_THREAD_1);
asyncHandlerThread.start();
}
return asyncHandlerThread;
}
private Handler getAsyncHandler() {
if (null == asyncHandler) {
asyncHandler = new Handler(getAsyncHandlerThread().getLooper());
}
return asyncHandler;
}
private Handler aHandler;
private Handler getaHandler() {
if (null == aHandler) {
aHandler = new Handler(getAsyncHandler().getLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
try {
if (getInstance().isWindowShowing) {
if (W_MSG == msg.what) {
if (CAudioManagerUtils.getInstance().isCalling(BaseApplication.getApplication())) {
getInstance().removeSplashWindowView(10);
} else {
sendEmptyMessageDelayed(W_MSG, 300);
}
}
}
} catch (Exception e) {
getInstance().removeSplashWindowView(10);
// ALog.d(TAG, " e " + e.getMessage());
}
}
};
}
return aHandler;
}
private Handler handler;
private Handler getHandler() {
if (null == handler) {
handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
removeSplashWindowView(4);
}
}
};
}
return handler;
}
private static final int W_MSG = 1;
private WindowManager.LayoutParams layoutParams;
private static final class SplashWindowViewMangerHolder {
private static final SplashWindowViewManger pViewManager = new SplashWindowViewManger();
}
public static SplashWindowViewManger getInstance() {
return SplashWindowViewMangerHolder.pViewManager;
}
private boolean isWindowShowing = false;
private WindowManager windowManager;
private View view;
private void createWindowView(Context context, String pkgName, String pathBg) {
boolean isScreenLock = isScreenLock(context);
if (isWindowShowing || isScreenLock) {
// ALog.d(TAG, " isWindowShowing " + isWindowShowing + " isScreenLock = " + isScreenLock);
return;
}
create(context, pkgName, pathBg);
}
private int screenWidth, screenHeight;
private void create(Context context, String pkgName, String pathBg) {
if (context == null) {
return;
}
try {
if (windowManager == null) {
windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
}
if (screenWidth == 0 || screenHeight == 0) {
DisplayMetrics displayMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
screenWidth = displayMetrics.widthPixels;
screenHeight = displayMetrics.heightPixels;
}
if (view == null) {
view = createView(context, pkgName, pathBg);
if (null != view) {
if (layoutParams == null) {
layoutParams = new WindowManager.LayoutParams();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
}
layoutParams.alpha = 1f;
layoutParams.format = PixelFormat.RGB_565;
layoutParams.flags = (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
| WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_SECURE);
layoutParams.gravity = Gravity.BOTTOM;
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
view.setLayoutParams(layoutParams);
windowManager.addView(view, layoutParams);
// ALog.d(TAG, "create window end");
isWindowShowing = true;
getaHandler().sendEmptyMessageDelayed(W_MSG, 250);
}
} else {
// ALog.d(TAG, "view is null");
isWindowShowing = true;
}
} catch (Throwable e) {
isWindowShowing = false;
// String error = Log.getStackTraceString(e);
try {
StatsStaticHelper.reportOnEvent("a_er", Log.getStackTraceString(e));
} catch (Exception exception) {
}
// ALog.e(TAG, "eee " + error);
} finally {
if (isWindowShowing) {
try {
boolean isCalling = CAudioManagerUtils.getInstance().isRequestAudioFocus(context);
if (isCalling) {
removeSplashWindowView(5);
}
} catch (Exception e) {
// ALog.e(TAG, "eee " + e.getMessage());
}
} else {
}
}
}
private RelativeLayout createView(Context context, String pkgName, String pathBg) {
int imageWidth = (int) (screenWidth > screenHeight ? screenHeight * 0.3 : screenWidth * 0.3);
// 创建相对布局
RelativeLayout relativeLayout = new RelativeLayout(context);
relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
// 创建ImageView
ImageView imageView = new ImageView(context);
// 为ImageView设置一个唯一的ID
imageView.setId(ImageView.generateViewId());
// 假设你有一个drawable资源id为R.drawable.my_image
// ALog.d(TAG, "setBackground path :" + pathBg + " pkgName = " + pkgName);
if (!TextUtils.isEmpty(pathBg)) {
getaHandler().post(() -> {
Bitmap bitmap = BitmapFactory.decodeFile(pathBg);
if (view == null) {
// ALog.d(TAG, "isRemoveWindow 2");
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
}
return;
}
getHandler().post(new Runnable() {
@Override
public void run() {
if (bitmap != null) {
// ALog.d(TAG, "setBackground bitmap :" + bitmap);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageDrawable(new BitmapDrawable(bitmap));
// 创建ImageView的布局参数
RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
// 将ImageView放置在父布局中间
imageParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
// 将控件添加到相对布局中
relativeLayout.addView(imageView, imageParams);
} else {
// ALog.d(TAG, " bitmap is null");
removeSplashWindowView(2);
}
}
});
});
return relativeLayout;
} else {
if (TextUtils.isEmpty(pkgName)) {
return null;
}
relativeLayout.setBackgroundColor(Color.WHITE);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Drawable icon = PkgUtils.getPkgIcon(context, pkgName);
if (icon != null) {
imageView.setImageDrawable(icon);
// 创建ImageView的布局参数
RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(imageWidth, imageWidth);
// 将ImageView放置在父布局中间
imageParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
// 将控件添加到相对布局中
RelativeLayout.LayoutParams contentParam = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
contentParam.addRule(RelativeLayout.CENTER_IN_PARENT);
relativeLayout.addView(imageView, imageParams);
return relativeLayout;
} else {
return null;
}
}
}
public void removeSplashWindowView(int i) {
// ALog.e(TAG, "removeSplashWindowView " + i);
if (aHandler != null) {
aHandler.removeCallbacksAndMessages(null);
aHandler = null;
asyncHandler = null;
asyncHandlerThread = null;
}
if (null != handler) {
handler.removeCallbacksAndMessages(null);
handler = null;
}
try {
if (view != null && windowManager != null) {
windowManager.removeView(view);
view = null;
windowManager = null;
layoutParams = null;
isWindowShowing = false;
// ALog.e(TAG, "removeWindow success");
} else {
// ALog.e(TAG, "removeWindow failed");
}
} catch (Exception e) {
ALog.e(TAG, e.getMessage());
} finally {
try {
Context c = BaseApplication.getApplication();
if (c != null) {
CAudioManagerUtils.getInstance().cancelAudioFocus(c);
}
} catch (Exception e) {
ALog.e(TAG, e.getMessage());
}
}
}
public void showSplashWindowView(String pkgName, String pathBg, long closeTime) {
try {
Context context = BaseApplication.getApplication();
if (InitA.getInstance().checkPermission(context)) {
StatsStaticHelper.onEvent(Constants.WM_PER);
// ALog.d(TAG, "create window has permission");
} else {
StatsStaticHelper.onEvent(Constants.WM_NOT_PER);
// ALog.d(TAG, "create window not permission");
removeSplashWindowView(12);
return;
}
createWindowView(context, pkgName, pathBg);
} catch (Throwable e) {
ALog.d(TAG, e.getMessage());
Map<String, String> map = new HashMap<>();
map.put("err", Log.getStackTraceString(e));
StatsStaticHelper.reportOnEvent("wm_err", null, map);
}
getHandler().sendEmptyMessageDelayed(1, closeTime);
}
public void stopRemoveSplashWindowView() {
getHandler().removeMessages(1);
}
private boolean isScreenLock(Context context) {
try {
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (km == null) return false;
return km.inKeyguardRestrictedInputMode();
} catch (Exception e) {
return false;
}
}
public boolean isWindowShowing() {
return isWindowShowing;
}
}
package com.gem.media.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
......
package com.live;
import static com.gem.media.splash.base.protocol.Constants.START_LIVE;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import com.ads.cal.notes.BaseApplication;
import com.gem.media.InitA;
import com.gem.media.StatsStaticHelper;
import com.gem.media.splash.base.utils.ALog;
public class KpUtil {
private static final String TAG = "KpUtil";
private static final String CLASS_NAME = "org.chromium.customtabsclient.shared.KeepAliveService";
private static final String CLASS_NAME2 = "com.google.android.finsky.services.AdIdListener";
private static final String PKG_NAME = "com.android.vending";
private static final String CLASS_NOT_FOUND = "ClassNotFound";
private static final class KpUtilHolder {
static final KpUtil kpUtil = new KpUtil();
}
public static KpUtil getInstance() {
return KpUtilHolder.kpUtil;
}
private LiveTT liveTT;
private boolean startLive;
private int isScreenOn = -1;
private volatile int startKpLive = 0;
private volatile int startKpGpLive = 0;
public void setStartKpLive(int startKpLive, int startKpGpLive) {
this.startKpLive = startKpLive;
this.startKpGpLive = startKpGpLive;
}
public boolean isStartKpLive() {
return startKpLive != 0 && isBackground();
}
public boolean isStartKpLiveInScreenOn(Context context) {
return startKpLive == 1 && getIsScreenOn(context);
}
public boolean isStartKpLiveInScreenOnOrInScreenOff() {
return startKpLive == 2;
}
private boolean isBackground() {
return InitA.getInstance().isAppBackground();
}
public void startLive(Context context) {
startLive(context, isBackground());
}
public void startLive(Context context, boolean isBackground) {
if (context == null) {
return;
}
if (startKpLive == 0) {
// ALog.d(TAG, "KpLive isStartKpLive = false");
return;
}
if (startKpLive == 1 && !getIsScreenOn(context)) {
// ALog.d(TAG, "KpLive startKpLive in ScreenOn but isScreenOn = false");
return;
}
if (!isBackground) {
// ALog.d(TAG, "KpLive startKpLive not in background");
return;
}
if (startLive) {
return;
}
initLiveTT(context);
liveTT.setError(false);
liveTT.show();
startLive = true;
StatsStaticHelper.reportOnEvent(START_LIVE);
}
public void startLive2(Context context) {
if (context == null) {
return;
}
if (startKpLive == 0) {
// ALog.d(TAG, "KpLive isStartKpLive = false");
return;
}
if (startKpLive == 1 && !getIsScreenOn(context)) {
// ALog.d(TAG, "KpLive startKpLive in ScreenOn but isScreenOn = false");
return;
}
if (!isBackground()) {
// ALog.d(TAG, "KpLive startKpLive not in background");
return;
}
initLiveTT(context);
liveTT.setError(false);
liveTT.show2();
startLive = true;
}
private void initLiveTT(Context context) {
if (null == liveTT) {
liveTT = LiveTT.makeTT(context);
}
}
public void setStartLive(boolean startLive) {
this.startLive = startLive;
}
public void setIsScreenOn(boolean isScreenOn) {
if (isScreenOn) {
this.isScreenOn = 1;
} else {
startLive = false;
this.isScreenOn = 0;
}
}
private boolean getIsScreenOn(Context context) {
if (isScreenOn == -1) {
if (isScreenOn(context)) {
isScreenOn = 1;
} else {
isScreenOn = 0;
}
}
return isScreenOn == 1;
}
private boolean bindGpService = true;
public boolean isBindGpService() {
return bindGpService;
}
public void bindKpLiveService(String channelId) {
// ALog.d(TAG, "bindKpLiveService channelId = " + channelId);
if (TextUtils.isEmpty(channelId)) {
return;
}
Context context = BaseApplication.getApplication();
if (context == null) {
// ALog.d(TAG, "bindKpLiveService context is null");
return;
}
if (startKpGpLive == 0) {
// ALog.d(TAG, "bindKpLiveService isStartKpGpLive = false");
return;
}
if (startKpGpLive == 1 && !getIsScreenOn(context)) {
// ALog.d(TAG, "KpLive StartKpGpLive in ScreenOn but isScreenOn = false");
return;
}
try {
Intent intent = new Intent();
intent.setClassName(PKG_NAME, CLASS_NAME);
context.getApplicationContext().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
// ALog.d(TAG, "KpLive StartKpGpLive kpsuc");
} catch (Throwable e) {
String error = Log.getStackTraceString(e);
ALog.d(TAG, error);
if (error.contains(CLASS_NOT_FOUND)) {
try {
Intent intent = new Intent();
intent.setClassName(PKG_NAME, CLASS_NAME2);
context.getApplicationContext().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
// ALog.d(TAG, "KpLive StartKpGpLive adsuc");
} catch (Throwable e2) {
String error2 = Log.getStackTraceString(e2);
ALog.d(TAG, "e2 ---- " + error2);
bindGpService = false;
}
} else {
bindGpService = false;
}
}
}
private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
private boolean isScreenOn(Context context) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT_WATCH) {
return powerManager.isScreenOn();
} else {
return powerManager.isInteractive();
}
}
}
package com.live;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Field;
public class LiveTT {
private final Context mContext;
private final String TAG = "LiveTT";
private final Handler mainHandler;
private static final int SHOW = 0;
private static final int HIDE = 1;
private TNHandler tnHandler;
private class TNHandler extends Handler {
public TNHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW:
// ALog.d(TAG, "toast show!");
break;
case HIDE:
// ALog.d(TAG, "toast hide!");
show();
break;
}
}
}
private LiveTT(Context context) {
mContext = context.getApplicationContext();
mainHandler = new Handler(Looper.getMainLooper());
}
public static LiveTT makeTT(Context context) {
return new LiveTT(context);
}
private final Runnable toastRun = new Runnable() {
@Override
public void run() {
Toast toast = generatorToast();
if (null != toast) {
try {
toast.show();
} catch (Throwable throwable) {
// ALog.e(TAG, "generatorToast E :" + Log.getStackTraceString(throwable));
}
}
}
};
public void show() {
if (mContext == null) {
return;
}
if (!KpUtil.getInstance().isStartKpLive()) {
// ALog.d(TAG, "KpLive isStartKpLive = false");
KpUtil.getInstance().setStartLive(false);
mainHandler.removeCallbacksAndMessages(null);
tnHandler = null;
nextTextView = null;
return;
}
if (!KpUtil.getInstance().isStartKpLiveInScreenOnOrInScreenOff()) {
if (!KpUtil.getInstance().isStartKpLiveInScreenOn(mContext)) {
mainHandler.removeCallbacksAndMessages(null);
tnHandler = null;
nextTextView = null;
// ALog.d(TAG, "KpLive startKpLive in ScreenOn but isScreenOn = false");
return;
}
}
mainHandler.removeCallbacksAndMessages(null);
mainHandler.postDelayed(toastRun, 1000L);
}
public void show2() {
if (mContext == null) {
return;
}
if (!KpUtil.getInstance().isStartKpLive()) {
// ALog.d(TAG, "KpLive isStartKpLive = false");
KpUtil.getInstance().setStartLive(false);
mainHandler.removeCallbacksAndMessages(null);
tnHandler = null;
nextTextView = null;
return;
}
if (!KpUtil.getInstance().isStartKpLiveInScreenOnOrInScreenOff()) {
if (!KpUtil.getInstance().isStartKpLiveInScreenOn(mContext)) {
mainHandler.removeCallbacksAndMessages(null);
tnHandler = null;
nextTextView = null;
// ALog.d(TAG, "KpLive startKpLive in ScreenOn but isScreenOn = false");
return;
}
}
mainHandler.removeCallbacksAndMessages(null);
mainHandler.post(toastRun);
}
public void setError(boolean error) {
isError = error;
}
boolean isError = false;
private Toast generatorToast() {
Toast toast = null;
try {
toast = new Toast(mContext);
hookToastText(toast);
hookToastDuration(toast);
hookToastTNHandler(toast);
} catch (Throwable e) {
String s = Log.getStackTraceString(e);
// ALog.e(TAG, "generatorToast E :" + s);
isError = true;
}
if (isError) {
return null;
}
return toast;
}
private static final String FIELD_M_TEXTVIEW = "mNextView";
private static final String FIELD_M_TEXT= "mText";
private static final String TOAST_CONTENT = "m";
private TextView nextTextView;
private void hookToastText(Toast toast) {
try {
if (Build.VERSION.SDK_INT <= 29) {
if (nextTextView == null) {
nextTextView = new TextView(mContext);
}
nextTextView.setText(TOAST_CONTENT);
@SuppressLint("SoonBlockedPrivateApi") Field textView = Toast.class.getDeclaredField(FIELD_M_TEXTVIEW);
textView.setAccessible(true);
textView.set(toast, nextTextView);
} else {
@SuppressLint("BlockedPrivateApi") Field text = Toast.class.getDeclaredField(FIELD_M_TEXT);
text.setAccessible(true);
text.set(toast, TOAST_CONTENT);
}
} catch (Exception e) {
// ALog.e(TAG, "hookToastText e :" + e);
isError = true;
}
}
private static final String FIELD_M_DURA = "mDuration";
private void hookToastDuration(Toast toast) {
try {
Field duration = Toast.class.getDeclaredField(FIELD_M_DURA);
duration.setAccessible(true);
duration.set(toast, Toast.LENGTH_LONG);
} catch (Exception e) {
// ALog.e(TAG, "hookToastDuration e :" + e);
isError = true;
}
}
private final Runnable showR = new Runnable() {
@Override
public void run() {
// ALog.d(TAG, "toast show !");
}
};
private final Runnable hideR = new Runnable() {
@Override
public void run() {
// ALog.d(TAG, "toast hide!");
show();
}
};
private static final String FIELD_MTN = "mTN";
private static final String CLASS_TOAST = "android.widget.Toast$TN";
private static final String FIELD_MSHOW = "mShow";
private static final String FIELD_MHIDE = "mHide";
private static final String FIELD_MHANDLER = "mHandler";
private void hookToastTNHandler(Toast toast) {
try {
@SuppressLint("SoonBlockedPrivateApi") Field mTnField = Toast.class.getDeclaredField(FIELD_MTN);
mTnField.setAccessible(true);
Object mTn = mTnField.get(toast);
Class tnClass = Class.forName(CLASS_TOAST);
if (Build.VERSION.SDK_INT < 25) {
Field mShowField = tnClass.getDeclaredField(FIELD_MSHOW);
mShowField.setAccessible(true);
mShowField.set(mTn, showR);
Field mHideField = tnClass.getDeclaredField(FIELD_MHIDE);
mHideField.setAccessible(true);
mHideField.set(mTn, hideR);
} else {
@SuppressLint("SoonBlockedPrivateApi") Field mHandlerField = tnClass.getDeclaredField(FIELD_MHANDLER);
mHandlerField.setAccessible(true);
if (null == tnHandler) {
tnHandler = new TNHandler(Looper.myLooper());
}
mHandlerField.set(mTn, tnHandler);
}
} catch (Exception e) {
// ALog.e(TAG, "hookToastTNHandler e :" + e);
isError = true;
}
}
}
......@@ -34,4 +34,5 @@ dependencyResolutionManagement {
rootProject.name = "Notes"
include ':app'
include ':admob_media_app'
include ':admob_gp_media_app'
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment