Commit e4fcd61a authored by wanglei's avatar wanglei

[同步]广告问题

parent 8a61fdb6
......@@ -18,18 +18,13 @@ import com.dumpster.cleaner.utils.SolarEngineUtils.initSolarEngine
import com.dumpster.cleaner.utils.SolarEngineUtils.solarkey
import com.facebook.FacebookSdk
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.gson.Gson
import com.hjq.language.MultiLanguages
import com.hjq.language.OnLanguageListener
import com.reyun.solar.engine.SolarEngineManager
import org.json.JSONObject
import java.util.Locale
import java.util.UUID
import com.dumpster.cleaner.SpConstObject.appLanguageSp
import com.dumpster.cleaner.SpConstObject.appLanguageCountrySp
import com.dumpster.cleaner.bean.config.AdConfigBean
import com.dumpster.cleaner.bean.config.ConfigBean
import com.dumpster.cleaner.bean.config.PopupConfigBean
import com.dumpster.cleaner.business.ads.AdsMgr
import com.dumpster.cleaner.business.helper.NewComUtils.spConfig
import com.dumpster.cleaner.business.push.fcm.FCMManager
......@@ -41,7 +36,9 @@ import com.dumpster.cleaner.business.push.work.RepeatingWorker.Companion.schedul
import com.dumpster.cleaner.ui.batteryinfo.BatteryReceiver.Companion.registerBatteryReceiver
import com.dumpster.cleaner.ui.splash.SplashActivity
import com.facebook.appevents.AppEventsLogger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
class MyApplication : Application() {
private val TAG = "MyApplication"
......@@ -73,6 +70,7 @@ class MyApplication : Application() {
initUUid()
initGid()
initApp()
initLifeListener()
initLanguage()
}
......@@ -99,12 +97,15 @@ class MyApplication : Application() {
})
}
private fun initGid() {
Thread {
private fun initGid() = MainScope().launch(Dispatchers.IO) {
try {
val info: AdvertisingIdClient.Info = AdvertisingIdClient.getAdvertisingIdInfo(applicationContext)
val advertisingId = info.id
AppPreferences.getInstance().put("gid", advertisingId)
}.start()
} catch (e: Exception) {
EventUtils.event("gid_exception")
}
}
override fun attachBaseContext(base: Context?) {
......@@ -123,17 +124,35 @@ class MyApplication : Application() {
fun initApp() {
kotlin.runCatching {
startStayJobService()
}
//初始化广告相关业务
AdsMgr.init(appContext)
initPush()
initAppConfig()
initFacebook()
initSolar()
}
private fun initSolar() {
SolarEngineManager.getInstance().preInit(this, solarkey)
appContext.initSolarEngine(true)
}
private fun initFacebook() {
//初始化facebook sdk
FacebookSdk.sdkInitialize(applicationContext)
AppEventsLogger.activateApp(this)
}
private fun initPush() {
kotlin.runCatching {
startStayJobService()
}
// val token = AppPreferences.getInstance().getString("token", "")
val topic = GlobalConfig.PACKAGE_NAME + "_push"
......@@ -141,12 +160,7 @@ class MyApplication : Application() {
FCMManager.initFirebase(this)
FCMManager.subscribeToTopic(topic)
initAppConfig()
SolarEngineManager.getInstance().preInit(this, solarkey)
initLifeListener()
changeTimer()
ScreenStatusReceiver.registerScreenStatusReceiver(this)
// PackageStatusReceiver.registerPackageStatusReceiver(this)
registerBatteryReceiver(this)
......@@ -160,19 +174,21 @@ class MyApplication : Application() {
//开启通知队列
MyNotificationManager.startNotificationQueue()
appContext.initSolarEngine(true)
}
private fun initAppConfig() {
Thread {
initConfig()
InstallHelps.init {
initRemoteConfig()
}
}.start()
//初始化sp的配置
NewComUtils.parseConfigBean(spConfig)
NewComUtils.requestCfgCallBackMap.put("changeTimer") {
LogEx.logDebug(TAG, "requestCfgCallBackMap changeTimer")
changeTimer()
}
InstallHelps.init {
NewComUtils.requestCfg()
}
}
private var lastTimePause = 0L
......@@ -204,7 +220,10 @@ class MyApplication : Application() {
noLoadingActivities.all { !topActivity.localClassName.contains(it, true) }
}
LogEx.logDebug(TAG, "flag=$flag" + " activity:" + activity.localClassName)
LogEx.logDebug(
TAG,
"flag=$flag" + " activity:" + activity.localClassName + " topActivity=${topActivity?.localClassName}"
)
if (flag) {
topActivity?.startActivity(
......@@ -240,46 +259,4 @@ class MyApplication : Application() {
})
}
private fun initRemoteConfig() {
NewComUtils.requestCfg { config ->
LogEx.logDebug("requestCfg", "config=$config")
if (config != null) {
initConfig(config)
} else {
EventUtils.event("configNull")
}
}
}
private fun initConfig(config: String = spConfig) {
if (config.isEmpty()) return
// kotlin.runCatching {
val configBean = Gson().fromJson(config, ConfigBean::class.java)
val jsonObject = JSONObject()
jsonObject.put("ut", configBean.ut)
EventUtils.event("user_type", ext = jsonObject)
//配置
ConfigBean.configBean = configBean
//广告
AdConfigBean.adsConfigBean = configBean.adConfigBean
LogEx.logDebug("initConfig", "adsConfigBean=${configBean.adConfigBean.functionInShowAd}")
//通知配置
PopupConfigBean.popupConfigBean = configBean.popupConfigBean
LogEx.logDebug("initConfig", "popupConfigBean=${configBean.popupConfigBean.popupCount}")
//启动定时器
changeTimer()
// }
}
}
\ No newline at end of file
......@@ -90,4 +90,15 @@ object SpConstObject {
AppPreferences.getInstance().put("fcmToken", value, true)
}
//是否上报过useType
var useTypeEvent = false
get() {
return AppPreferences.getInstance().getBoolean("useTypeEvent", field)
}
set(value) {
field = value
AppPreferences.getInstance().put("useTypeEvent", value, true)
}
}
\ No newline at end of file
......@@ -49,7 +49,6 @@ object AdsMgr {
private val adBannerMgr by lazy {
AdBannerMgr()
}
private val maxOpenMgr by lazy {
MaxOpenMgr()
}
......@@ -110,8 +109,8 @@ object AdsMgr {
if (adsConfigBean.adSwitch) {
admobInitCallBack?.invoke()
admobInitCallBack = null
adNativeMgr.loadAd(MyApplication.appContext, AdmobEvent("nativeAd", "preload"), null)
// adOpenMgr.loadAd(context, true, AdmobEvent("openAd", context::class.java.simpleName))
adNativeMgr.loadAd(context, AdmobEvent("nativeAd", context::class.java.simpleName))
adOpenMgr.loadAd(context, AdmobEvent("openAd", context::class.java.simpleName))
adInterMgr.loadAd(context, AdmobEvent("interAd", context::class.java.simpleName))
}
}
......@@ -181,12 +180,13 @@ object AdsMgr {
val from = activity::class.java.simpleName
if (adsConfigBean.adSwitch) {
val admobEvent = AdmobEvent("openAd", from).apply { this.isUnLimit = isUnLimit }
if (isAdmobInit) {
adOpenMgr.show(activity, isUnLimit, AdmobEvent("openAd", from), showCallBack)
adOpenMgr.show(activity, admobEvent, showCallBack)
} else {
admobInitCallBack = {
}
adOpenMgr.show(activity, isUnLimit, AdmobEvent("openAd", from), showCallBack)
adOpenMgr.show(activity, admobEvent, showCallBack)
}
} else {
if (isMaxInit) {
......@@ -227,7 +227,7 @@ object AdsMgr {
LogEx.logDebug("showAd", "adSwitch=${adsConfigBean.adSwitch}")
val from = activity::class.java.simpleName
if (adsConfigBean.adSwitch) {
adInterMgr.show(activity, isUnLimit, AdmobEvent("interAd", from), showCallBack)
adInterMgr.show(activity, AdmobEvent("interAd", from).apply { this.isUnLimit = isUnLimit }, showCallBack)
} else {
maxInsertMgr.show(activity, isUnLimit, AdMaxEvent("interAd", from), showCallBack)
}
......@@ -245,8 +245,8 @@ object AdsMgr {
nativeCallBack: ((Any?) -> Unit)? = null
) {
if (!adsConfigBean.isAdShow) {
nativeCallBack?.invoke(null)
nativeView.visibility = View.GONE
nativeCallBack?.invoke(null)
return
}
nativeView.visibility = View.VISIBLE
......@@ -290,4 +290,5 @@ object AdsMgr {
adBannerMgr.show(parent, collapsible, adClose)
}
}
}
\ No newline at end of file
......@@ -17,6 +17,13 @@ object InstallHelps {
fun init(requestCfg: () -> Unit) {
val installReferrer = AppPreferences.getInstance().getString("install_referrer", "")
if (installReferrer.isNotEmpty()) {
requestCfg.invoke()
return
}
val referrerClient = InstallReferrerClient.newBuilder(MyApplication.appContext).build()
referrerClient.startConnection(object : InstallReferrerStateListener {
override fun onInstallReferrerSetupFinished(responseCode: Int) {
......
......@@ -4,20 +4,26 @@ import android.util.Base64
import android.util.Log
import com.dumpster.cleaner.BuildConfig
import com.dumpster.cleaner.GlobalConfig
import com.dumpster.cleaner.SpConstObject.useTypeEvent
import com.dumpster.cleaner.bean.config.AdConfigBean
import com.dumpster.cleaner.bean.config.ConfigBean
import com.dumpster.cleaner.bean.config.PopupConfigBean
import com.dumpster.cleaner.utils.AppPreferences
import com.dumpster.cleaner.utils.LogEx
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException
import java.util.Locale
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object NewComUtils {
private val TAG = "NewComUtils"
private const val API_URL = GlobalConfig.URL_API
private const val PACKAGE_NAME_PREFIX = GlobalConfig.PACKAGE_NAME
......@@ -43,7 +49,8 @@ object NewComUtils {
AppPreferences.getInstance().put("lastRequestTime", value, true)
}
private val url: String by lazy {
fun getUrl(): String {
val packageName = GlobalConfig.PACKAGE_NAME
val appCode = packageName.substringAfter(PACKAGE_NAME_PREFIX).take(5).toLowerCase(Locale.getDefault())
......@@ -63,79 +70,147 @@ object NewComUtils {
s = "$s&mode=4"
}
s
// mode =3 google mode=2 facebook mode=1 自然,mode=4 测试
// mode =3 google mode=2 facebook mode=1 自然,mode=4 测试
// &mode=3
return s
}
var requestCfgCallBack: (() -> Unit)? = null
//请求中的回调
var requestCfgIng = AtomicBoolean(false)
fun requestCfg(callback: (json: String?) -> Unit) {
fun canRequestCfg(): Boolean {
val passHour = (System.currentTimeMillis() - lastRequestTime) / 3600000
CoroutineScope(Dispatchers.IO).launch {
requestCfgIng.set(true)
val passHour = (System.currentTimeMillis() - lastRequestTime) / 3600000
if (BuildConfig.DEBUG) {
lastRequestTime = 0L
}
if (BuildConfig.DEBUG) {
lastRequestTime = 0L
}
if (lastRequestTime != 0L && passHour < ConfigBean.configBean.getConfigInterval) {
Log.e(TAG, "请求间隔 passHour=$passHour")
return false
}
if (lastRequestTime != 0L && passHour < ConfigBean.configBean.getConfigInterval) {
callback.invoke(null)
Log.e(TAG, "请求间隔 passHour=$passHour")
return@launch
}
return true
}
fun requestCfg() {
val response = doGet()
if (response == null) {
callback(null)
return@launch
}
requestCfgIng.set(true)
if (!canRequestCfg()) {
return
}
val data = extractData(response)
if (data == null) {
callback(null)
return@launch
val urlPath = getUrl()
LogEx.logDebug(TAG, "url=$urlPath")
val request = Request.Builder()
.url(urlPath)
.get()
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
Log.d(TAG, "onFailure $e")
handleCfgCallBack()
}
lastRequestTime = System.currentTimeMillis()
val decryptedData = AESHelper.decrypt(data)
LogEx.logDebug(TAG, "decryptedData=$decryptedData")
spConfig = decryptedData
callback(decryptedData)
override fun onResponse(call: Call, response: Response) {
requestCfgIng.set(false)
if (response.isSuccessful) {
val json = response.body?.string() ?: ""
LogEx.logDebug(TAG, "json=$json")
requestCfgCallBack?.invoke()
requestCfgCallBack = null
val data = extractData(json)
if (data != null) {
}
}
lastRequestTime = System.currentTimeMillis()
val decryptedData = AESHelper.decrypt(data)
LogEx.logDebug(TAG, "decryptedData=$decryptedData")
parseConfigBean(decryptedData)
}
}
private fun doGet(): String? {
val urlPath = url
LogEx.logDebug(TAG, "url=$url")
try {
val conn: HttpURLConnection = URL(urlPath).openConnection() as HttpURLConnection
conn.setRequestMethod("GET")
conn.connectTimeout = 150000
if (200 == conn.getResponseCode()) {
val json = BufferedReader(InputStreamReader(conn.inputStream)).readLine()
LogEx.logDebug(TAG, "json=$json")
return json
handleCfgCallBack()
}
} catch (e: Exception) {
e.printStackTrace()
Log.d("okhttp", e.toString())
}
return null
})
}
private val client = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.callTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build()
private fun extractData(response: String): String? {
val regex = Regex("\"$DATA_KEY\":\"(.*?)\"")
val match = regex.find(response)
return match?.groupValues?.get(1)
}
fun parseConfigBean(config: String) {
if (config.isNotEmpty()) {
try {
val configBean = Gson().fromJson(config, ConfigBean::class.java)
if (!useTypeEvent) {
val jsonObject = JSONObject()
jsonObject.put("ut", configBean.ut)
EventUtils.event("user_type", ext = jsonObject)
useTypeEvent = true
}
//配置
ConfigBean.configBean = configBean
//广告
AdConfigBean.adsConfigBean = configBean.adConfigBean
LogEx.logDebug("initConfig", "adsConfigBean=${configBean.adConfigBean.isAdShow} ut=${configBean.ut}", true)
//通知配置
PopupConfigBean.popupConfigBean = configBean.popupConfigBean
LogEx.logDebug("initConfig", "popupConfigBean=${configBean.popupConfigBean.popupCount}", true)
if (spConfig != config) {
spConfig = config
}
} catch (e: Exception) {
e.printStackTrace()
LogEx.logDebug("initConfig", "parseConfigBean_error", true)
EventUtils.event("parseConfigBean_error", value = config)
}
}
}
var requestCfgCallBackMap = hashMapOf<String, () -> Unit>()
private fun handleCfgCallBack() {
requestCfgIng.set(false)
LogEx.logDebug(TAG, "handleCfgCallBack")
val key1 = "adCallBack"
requestCfgCallBackMap.get(key1)?.let {
it.invoke()
requestCfgCallBackMap.remove(key1)
}
val key2 = "changeTimer"
requestCfgCallBackMap.get(key2)?.let {
it.invoke()
requestCfgCallBackMap.remove(key2)
}
}
}
package com.dumpster.cleaner.business.helper;
import android.text.TextUtils;
import com.dumpster.cleaner.utils.LogEx;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class ReportUtils {
private static String TAG = "ReportUtils";
public static String doPost(String urlPath, Map<String, String> paramsMap, String json) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(urlPath).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
if (!TextUtils.isEmpty(json)) {
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Length", Integer.toString(json.getBytes().length));
conn.getOutputStream().write(json.getBytes());
}
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
result.append("&").append(entry.getKey()).append("=").append(entry.getValue());
}
if (result.length() > 0) {
try {
conn.getOutputStream().write(result.substring(1).getBytes());
} catch (Exception e) {
}
} else {
// conn.getOutputStream().write(result.substring(0).getBytes());
}
if (conn.getResponseCode() == 200) {
String s = new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();
if (!TextUtils.isEmpty(s)) {
} else {
s = "";
}
LogEx.INSTANCE.logDebug(TAG, "code=200", false);
return s;
} else {
LogEx.INSTANCE.logDebug(TAG, "code!=200", false);
}
} catch (Exception e) {
e.printStackTrace();
}
return "{ \"success\": false,\n \"errorMsg\": \"后台服务器开小差了!\",\n \"result\":{}}";
}
}
......@@ -31,7 +31,6 @@ import com.dumpster.cleaner.business.ads.AdsMgr
import com.dumpster.cleaner.business.ads.AdsShowCallBack
import com.dumpster.cleaner.business.helper.EventUtils
import com.dumpster.cleaner.business.helper.NewComUtils
import com.dumpster.cleaner.business.helper.NewComUtils.requestCfgCallBack
import com.dumpster.cleaner.business.helper.NewComUtils.spConfig
import com.dumpster.cleaner.business.service.StayJobService.Companion.startStayJobService
import com.dumpster.cleaner.databinding.ActivitySplashBinding
......@@ -213,7 +212,8 @@ class SplashActivity : BaseActivity<ActivitySplashBinding>(ActivitySplashBinding
acAction.invoke()
} else {
if (NewComUtils.requestCfgIng.get()) {
requestCfgCallBack = {
NewComUtils.requestCfgCallBackMap.put("adCallBack") {
Log.e(TAG, "requestCfgCallBack")
lifecycleScope.launch(Dispatchers.Main) {
Log.e(TAG, "2")
acAction.invoke()
......
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