Android appの実装
サンプルコードを例に、advertising_idなどの受け渡し、そのほか実装上の注意事項に関して説明します。
- JavaScriptとの連携方法
- Webページにデータ取得用のインターフェース作成
- Webページからadvertising_id,appbundle,platformvを取得する
- 広告リダイレクトの対応
- その他WebViewの設定
JavaScriptとの連携方法
ネイティブアプリにデータ取得用のインターフェース作成
クラス作成
- Kotlin
- Java
import android.os.Build
class WebAppInterface {
companion object {
private const val TAG = "WebAppInterface"
}
private var advertising_id: String? = ""
private var isLAT: Boolean = false
private lateinit var context: Context
constructor(ct: Context) {
this.context = ct
this.initAdIdThread()
}
private fun initAdIdThread() {
val adIdThread = Thread {
var adInfo: AdvertisingIdClient.Info? = null
try {
adInfo = AdvertisingIdClient
.getAdvertisingIdInfo(this.context)
advertising_id = adInfo.id
isLAT = adInfo.isLimitAdTrackingEnabled
} catch (e: Exception) {
Log.d(TAG, "getAdId failed")
}
}
adIdThread.start()
}
@JavascriptInterface
open fun getAppBundle(): String {
return this.context.packageName ?: ""
}
@JavascriptInterface
open fun getAdvertisingId(): String {
val adid = advertising_id ?: ""
return if (!isLAT) adid else ""
}
@JavascriptInterface
open fun getPlatformV(): String {
return Build.VERSION.RELEASE
}
}
import android.os.Build;
public class WebAppInterface {
private static final String TAG = "WebAppInterface";
private String advertising_id = "";
private boolean isLAT = false;
private Context context;
public WebAppInterface(Context ct) {
this.context = ct;
this.initAdIdThread();
}
private void initAdIdThread() {
Thread adIdThread = new Thread(new Runnable() {
@Override
public void run() {
AdvertisingIdClient.Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
advertising_id = adInfo.getId();
isLAT = adInfo.isLimitAdTrackingEnabled();
} catch (Exception e) {
Log.d(TAG, "getAdId failed");
}
}
});
adIdThread.start();
}
@JavascriptInterface
public String getAppBundle() {
return context.getPackageName();
}
@JavascriptInterface
public String getAdvertisingId() {
String adid = advertising_id;
return !isLAT ? adid : "";
}
@JavascriptInterface
public String getPlatformV() {
return Build.VERSION.RELEASE;
}
}
javascriptから処理を呼び出せるように設定
- Kotlin
- Java
val context = applicationContext
webView.addJavascriptInterface(WebAppInterface(context), "Android")
webView.addJavascriptInterface(new WebAppInterface(getApplicationContext()), "Android");
Webページからadvertising_id,appbundle,platformvを取得する
const advertising_id = Android.getAdvertisingId();
const appbundle = Android.getAppBundle();
const platformv = Android.getPlatformV();
取得したadid,packageNameを利用し 広告タグにパラメータを生成してください。
{〜}が置換部分となります。値はURLエンコードを行ってください。
AdvertisingIDについては、端末側でオプトアウトされている場合は付与しないようにご注意ください。
<div id="adg_area"></div>
<script>
/*
idfa : iOSの場合この変数にidfaがセットされているとする(オプトアウト時除く)
aaid : Androidの場合この変数にAdvertising IDがセットされているとする(オプトアウト時除く)
appbundle : 実際にはこの変数にBundle IDかPackage Nameがセットされているとする。
platformv : iOS/Androidのバージョンがセットされているとする。
*/
(function() {
const div = document.getElementById("adg_area");
const script = document.createElement('script');
script.type = 'text/javascript';
let idfa = window?.adgAdParams?.idfa ?? "";
let advertising_id = window?.Android?.getAdvertisingId?.() ?? "";
let appbundle = window?.adgAdParams?.appbundle ?? window?.Android?.getAppBundle?.() ?? "";
let platformv = window?.adgAdParams?.platformv ?? window?.Android?.getPlatformV?.() ?? "";
// scriptのsrcにセットするテキストは実際に管理画面から取得されるタグのsrcと合わせてください。ただし、asyncは必ずtrueにしてください。
let srcText ='https://i.socdm.com/sdk/js/adg-script-loader.js?id=48547&targetID=adg_48547&displayid=1&adType=SP&async=true&tagver=2.0.0';
if(idfa.length > 0){
srcText += '&idfa=' + encodeURIComponent(idfa);
}
else if(advertising_id.length > 0){
srcText += '&advertising_id=' +encodeURIComponent(advertising_id);
}
if(appbundle.length > 0){
srcText += '&appbundle=' + encodeURIComponent(appbundle);
}
if(platformv.length > 0){
srcText += '&platformv=' + encodeURIComponent(platformv);
}
script.src =srcText;
if(div != null){
div.appendChild(script);
}
})();
</script>
広告リダイレクトの対応
配信される広告のタップ動作によって、外部のサイトへ移動したり Google Playのリンクなどを開けるようにする。 サンプルではドメインによって、外部サイトを判定しています。
- Kotlin
- Java
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?,
): Boolean {
Log.d(TAG, "shouldOverrideUrlLoading")
if (request?.url?.host == null) {
return false
}
val currentDomain = URL(view?.url).host
// http-httpsではないものは別
if (!request.url.scheme.equals("http") &&
!request.url.scheme.equals("https")
) {
val intent = Intent(Intent.ACTION_VIEW, request.url)
// If the URL cannot be opened, return early.
try {
Log.d(TAG, "Handle custom URL schemes ${request.url.scheme}")
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
}
} catch (exception: ActivityNotFoundException) {
Log.d("TAG", "Failed to load URL with scheme: ${request.url.scheme}")
}
return true
}
// 現在のドメインと遷移先のドメインが異なれえば外部のサイトだと判定する
val targetDomain = request?.url?.host
if (!currentDomain.equals(targetDomain)) {
// 外部のサイト
Log.d(TAG, "external Web Site ${request.url.scheme}")
val intent: CustomTabsIntent = CustomTabsIntent.Builder().build()
intent.launchUrl(this@MainActivity, request.url)
return true
}
// 同一サイト
return false
}
override fun doUpdateVisitedHistory(view: WebView?, url: String?, isReload: Boolean) {
onBackPressedCallback.isEnabled = webView.canGoBack()
}
}
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
Log.d(TAG, "shouldOverrideUrlLoading");
if (request.getUrl().getHost() == null) {
return false;
}
// http-httpsではないものは別
if (!request.getUrl().getScheme().equals("http") &&
!request.getUrl().getScheme().equals("https")) {
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
// If the URL cannot be opened, return early.
try {
Log.d(TAG, "Handle custom URL schemes " + request.getUrl().getScheme());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} catch (ActivityNotFoundException exception) {
Log.d(TAG, "Failed to load URL with scheme: " + request.getUrl().getScheme());
}
return true;
}
String currentDomain;
try {
currentDomain = new URL(view.getUrl()).getHost();
} catch ( MalformedURLException exception) {
// 不正なURL
return false;
}
// 現在のドメインと遷移先のドメインが異なれえば外部のサイトだと判定する
String targetDomain = request.getUrl().getHost();
if (!currentDomain.equals(targetDomain)) {
// 外部のサイト
Log.d(TAG, "external Web Site " + request.getUrl().getScheme());
CustomTabsIntent intent = new CustomTabsIntent.Builder().build();
intent.launchUrl(MainActivity.this, request.getUrl());
return true;
}
// 同一サイト
return false;
}
その他WebViewの設定
以下の点を対応してください。
- cookieの有効化
- JavaScriptの有効化
- LocalStorage有効化
- 動画の自動再生許可
- Kotlin
- Java
// cookieを利用できるようにする
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
// JavaScript有効化
webView.settings.javaScriptEnabled = true
// LocalStorage有効化
webView.settings.domStorageEnabled = true
// 動画の自動再生許可
webView.settings.mediaPlaybackRequiresUserGesture = false
// cookieを利用できるようにする
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
// JavaScript有効化
webView.getSettings().setJavaScriptEnabled(true);
// LocalStorage有効化
webView.getSettings().setDomStorageEnabled(true);
// 動画の自動再生許可
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);