# MPM SDK設定

IMQA MPMには様々なオプションが存在します。ユーザーが希望する設定を追加することで、より詳細なクラッシュレポートを受け取ることができます。

## 1. MPMインストールオプション <a href="#mpm" id="mpm"></a>

### MPMオプションファイル <a href="#file" id="file"></a>

IMQA用設定ファイルを通して設定を管理することができます。当該ファイルは、appレベルの位置に置いておかなければなりません。

{% code title="(project root)/(app)/imqa-service.json" %}

```json
{
  "stop" : true,
  "mpm" : false,
  "crash" : true,
  "core" : true,
  "repackaging" : false,
  "lifecycle" : true,
  "event_listener" : true,
  "library_activity" : true,
  "fragment_lifecycle" : true,
  "webview" : true,
  "network" : true,
  "build_location" : "",
  "flavor" : "",
  "manifest_location" : "",
  "mapping_upload" : true,
  "map_upload_server" : "",
  "project_key" : "IMQA_KEY",
  "runtime" : {
    "buildType" : false,
    "printLog" : true,
    "dump_interval" : 1000,
    "file_interval" : 5,
    "upload_period" : true,
    "network_collect" : true,
    "socket_tracing" : false,
    "http_tracing" : true,
    "keep_file_on_fail" : true,
    "force_https" : false,
    "end_date" : "",
    "os_version_limit_list" : [],
    "app_version_limit_list" : [],
    "dump_size_max" : 10,
    "behavior_max" : 100
  }
}
```

{% endcode %}

### Fileビルド設定値について <a href="#option-name" id="option-name"></a>

<table><thead><tr><th width="150" align="center">Option Name</th><th width="196.92502258355918" align="center">Default Value</th><th width="364.2">Description</th></tr></thead><tbody><tr><td align="center">stop</td><td align="center">false</td><td>MPMのすべてのInjecting過程を実行します。\n trueに設定すると、すべての実行過程が無視されます。</td></tr><tr><td align="center">mpm</td><td align="center">true</td><td>MPM用SDKをインストールします。falseに設定すると、MPMライブラリを使用できません。</td></tr><tr><td align="center">crash</td><td align="center">true</td><td>Crash用SDKをインストールします。falseに設定すると、Crashライブラリを使用できません。</td></tr><tr><td align="center">core</td><td align="center">true</td><td>IMQA Core SDKをインストールします。falseに設定すると、Coreライブラリを使用できません。</td></tr><tr><td align="center">repackaging</td><td align="center">true</td><td>Repackagingモードを設定します。falseに設定すると、Compile中にInjectを実行します。</td></tr><tr><td align="center">lifecycle</td><td align="center">true</td><td>Activity Lifecycle Injectingを許可します。falseに設定すると、アクティビティマップが表示されません。</td></tr><tr><td align="center">event_listener</td><td align="center">true</td><td>Event Listener Injectingを許可します。falseに設定すると、イベント情報が収集されません。</td></tr><tr><td align="center">fragment_lifecycle</td><td align="center">true</td><td>Fragmentの収集状態を設定します。falseに設定すると、Fragmentのレンダリング速度が収集されません。</td></tr><tr><td align="center">webview</td><td align="center">true</td><td>WebViewに関するInjectingを許可します。falseに設定すると、ウェブビュー内のHTTP/Sリクエストが収集されません。</td></tr><tr><td align="center">network</td><td align="center">true</td><td>Network収集メソッドをラップ(Wrap)します。falseに設定すると、Network関連のレスポンスタイムが収集されません。</td></tr><tr><td align="center">manifest_location</td><td align="center">""</td><td>現在のビルド環境のManifest位置を直接設定します。未設定の場合、プラグインが自動的に検索されます。</td></tr><tr><td align="center">flavor</td><td align="center">""</td><td>現在のビルド環境のFlavorを直接設定します。未設定の場合、プラグインが自動的に検索されます。</td></tr><tr><td align="center">mapping_upload</td><td align="center">true</td><td>Mapping Fileを作成すると、自動的にアップデートされます。</td></tr><tr><td align="center">map_upload_server</td><td align="center">"http://mpm.imqa.io"</td><td>Network収集メソッドをラップ(Wrap)します。falseに設定すると、Network関連のレスポンスタイムが収集されません。</td></tr><tr><td align="center">project_key</td><td align="center">""</td><td>現在のアプリのプロジェクトキーを設定します。mapping.txtファイルをすぐにアップロードする場合は、設定する必要があります。未設定の場合、Build Logにアップロード失敗メッセージが表示されます。</td></tr></tbody></table>

### **File**ランタイム設定値について <a href="#runtime" id="runtime"></a>

<table><thead><tr><th width="150" align="center">Option Name</th><th width="150" align="center">Default Value</th><th width="299.2">Description</th></tr></thead><tbody><tr><td align="center">buildType</td><td align="center">false</td><td><p>IMQAのデータ収集可否を設定します。</p><p>- true:データを収集しません。</p><p>- false:データを収集します。</p></td></tr><tr><td align="center">printLog</td><td align="center">false</td><td>Logの出力状態を設定します。trueに設定すると、IMQAのLogが出力されます。</td></tr><tr><td align="center">dump_interval</td><td align="center">5000</td><td>ダンプの間隔をms(ミリ秒)単位に設定します。</td></tr><tr><td align="center">file_interval</td><td align="center">5</td><td>ダンプが保存されるファイルの間隔を分単位に設定します。</td></tr><tr><td align="center">upload_period</td><td align="center">false</td><td>ファイルアップロードを周期的に送信するかを設定します。アプリが実行中にFileIntervalの間隔に合わせてアップロードされます。falseに設定すると、アプリを再実行する場合のみ収集データがアップロードされます。</td></tr><tr><td align="center">socket_tracing</td><td align="center">true</td><td>Socket関連情報の収集機能を設定します。trueに設定すると、アプリ実行中にSocketを利用してネットワーク通信情報が収集・保存されます。</td></tr><tr><td align="center">http_tracing</td><td align="center">true</td><td>HTTP関連情報の収集機能を設定します。trueに設定すると、アプリ実行中にHTTP情報が収集・保存されます。</td></tr><tr><td align="center">keep_file_on_fail</td><td align="center">true</td><td>測定された性能ファイルを成功するまで残しておくかを設定します。アップロードに成功するまでファイルは内部に保存されます。falseに設定すると、アップロードに失敗してもファイルは削除されます。</td></tr><tr><td align="center">mpm_server_url</td><td align="center"><a href="http://collector.imqa.io">http://collector.imqa.io</a></td><td>MPMサーバーURLを設定します。</td></tr><tr><td align="center">force_https</td><td align="center">false</td><td>trueに設定すると、アップロードサーバーの認証書(SSL)を無視してHTTPS通信が実行されます。</td></tr><tr><td align="center">end_date</td><td align="center">(なし)</td><td>終了日を設定します。</td></tr><tr><td align="center">os_version_limit_list</td><td align="center">[ ]</td><td>動作するOSバージョンを設定します。</td></tr><tr><td align="center">app_version_limit_list</td><td align="center">[ ]</td><td>動作するアプリバージョンを設定します。</td></tr><tr><td align="center">dump_size_max</td><td align="center">10</td><td>ダンプデータ最大容量を設定します。(単位 MB)</td></tr><tr><td align="center">behavior_max</td><td align="center">15</td><td>行動分析データの最大個数を設定します。</td></tr></tbody></table>

### **Gradle File** <a href="#gradle" id="gradle"></a>

radleを利用すると、IMQA MPMインストールモードを変更することができます。&#x20;

{% code title="app.gradle" %}

```java
ext {
    /**
     * @Default false
     * Executes all injecting processes of MPM. 
     * All execution processes are ignored if set to true.
     */
    IMQAStop = false

    /**
     * @Default true
     * Allows activity lifecycle injecting.  
     * The activity map is hidden if set to false.
     */
    IMQALifecycle = true

    /**
     * @Default true
     * Allows event listener injecting.
     * Event information is not collected if set to false.
     */
    IMQAEventListener = true

    /**
     * @Default false
     * Allows injecting related to WebView.
     * HTTP/S requests in the WebView are not collected if set to false.
     */
    IMQAWebview = false

    /**
     * @Default true
     * Sets whether to collect fragments or not.
     * The rendering speed of the fragment is not collected if set to false.
     */
    IMQAFragment = true

    /**
     * @Default true
     * Wraps the network collection method.
     * Network-related response speed is not collected if set to false.
     */
    IMQANetwork = true

    /**
     * @Default ""
     * You can manually set the flavor of the current build environment.
     * The plugin automatically searches if not set.
     */
    IMQAFlavor = "debug";

    /**
     * @Default "/build/intermediates/manifests/full/"
     * You can manually set the manifest location of the current build environment.
     * The plugin automatically searches if not set.
     */
    IMQAManifestLocation = "/build/intermediates/manifests/full/"

    /**
     * @Default true
     * Sets repackaging mode.
     * Injection is performed during compilation if set to false.
     */
    IMQARepackaging = false

    /**
     * @Default true
     * Automatically uploads a mapping file when it is created.
     * If not set, “mapping.txt” for each app version should be uploaded by connecting to IMQA.
     */
    IMQAMappingUpload = true

    /**
     * @Default ""
     * Sets the project key for the current app.
     * Additional setting is required to upload the “mapping.txt” file properly.
     * An upload failure message may appear in the build log if not set.
     */
    IMQAProjectKey = "";

    /**
     * @Default "http://mpm.imqa.io"
     * Input the host name to upload the “mapping.txt” file.
     * Additional setting is required to upload the “mapping.txt” file properly.
     * An upload failure message may appear in the build log if not set.
     */
    IMQAMapUploadServer = "http://mpm.imqa.io"

}
```

{% endcode %}

### MPM Run Option <a href="#run-option" id="run-option"></a>

IMQA MPMモードをパラメータやOptionを利用して変更することができます。

{% code title="MyApplication.java" %}

```java
@Override
public void onCreate() {
    super.onCreate();
    
    io.imqa.core.IMQAOption imqaOption = new io.imqa.core.IMQAOption();

    /*
     *  Default value : true 
     *  Sets execution mode. 
     *  true: Runs in release mode only.
     *  false: Runs in debug mode only. 
    */
    imqaOption.setBuildType(false);

    /*
     * Default value : false
     * Sets whether to output the log. 
     * true: Outputs the IMQA log.
    */
    imqaOption.setPrintLog(true);

    /*
     * Default value : 5000 (ms)
     * Sets the dump interval in ms (milliseconds).
    */
    imqaOption.setDumpInterval(3000);

    /*
     * Default value: 5 (minutes).
     * Sets the interval of saving dumps in a file in minutes.
    */
    imqaOption.setFileInterval(1);

    /*
     * Default value: false
     * Sets whether to upload a file periodically.
     * true: Uploads a file according to the FileInterval while the app is running.
     * false: Uploads collected data while executing the app again.
    */
    imqaOption.setUploadPeriod(true);

    /*
     * Deprecated
     * Default value: true
     * Sets the function of collecting information related to the socket.
     * true: Collects and saves network communication information using the socket while the app is running.
     * false: The IMQA socket collection function is not set.
    */
    imqaOption.setNetworkTracing(false);

    /*
     * Default value: true
     * Sets the function of collecting information related to the socket.
     * true: Collects and saves network communication information using the socket while the app is running.
     * false: The IMQA socket collection function is not set.
    */
    imqaOption.setSocketTracing(false);

    /*
     * Default value: true
     * Sets the function of collecting HTTP related information.
     * true: Collects and saves HTTP information while the app is running.
     * false: The IMQA HTTP collection function is not set.
    */
    imqaOption.setHttpTracing(false);

    /*
     * Default value: true
     * Sets whether to leave the measured performance file until upload is successful.
     * true: Keeps the file inside until the upload is successful.
     * false: The file is deleted even if upload fails.
    */
    imqaOption.setKeepFileAtUploadFail(false);

    /*
     * Default value: false
     * Establishes HTTPS communication by ignoring the certificate (SSL) of the upload server.
     * true: Ignores the certificate and establishes HTTPS communication.
     * false: Checks the certificate and establishes HTTPS communication.
     */
    imqaOption.setForceHttps(true);

    /*
     * Default value : null
     * Sets the end date.
     * Date: End date
     */
    imqaOption.setEndDate(Date);

    /*
     * Default value : false
     * Gets option settings from the server. Requests to the collection server set with setServerUrl.
     * Sets as the highest priority option. If not responded, it will be operated with the option set in the code.
     * true: Gets options from the server.
     * false: Operates with the option set in the code.
     */
    imqaOption.setRemoteConfig(true);

    /*
     * Default value : 3000
     * Sets a time-out when getting remote server options.
     * When a time-out occurs, it operates with the option set in the code.
     * int : timeout (ms)
     */
    imqaOption.setRemoteTimeout(3000);

    /*
     * 기본값 : ArrayList<Integer>
     * Sets the OS version to run.
     * int : Running OS version
     */
    imqaOption.addOSVersionLimitList(Build.VERSION_CODES.O);

    /*
     * Default value : OSProhibit
     * Does not activate the SDK under the version in question.
     * int : Running OS version
     */
    imqaOption.getOSProhibitVersionLimitList().addOSProhibitVersionLimitBelow(Build.VERSION_CODES.M);

    /*
     * Default value : ArrayList<String>
     * Sets the app version to run.
     * String : Running app version
     */
    imqaOption.addAppVersionLimitList("1.1");


    /*
     * Default value : null
     * Specifies the URL that will be excluded from collection.
     * By default, host and pathname will apply. Query value match can be added as an option.
     * String : Target url
     * boolean : query matching status (e.g.,: After the question mark (?) in https://abc.com/search?foo=bar)
     */
    imqaOption.getURLBlacklist().addBlacklistURL("https://abc.com/search", false);

    /*
     * Default value : ArrayList<AccessPoint>
     * Sets the app version to run.
     * One AP for each AccessPoint object. If no unique value is set among three options, it will be deemed true.
     * As SSID and BSSID require location authority,
     * “ACCESS_FINE_LOCATION” or “ACCESS_COARSE_LOCATION” should be added to use this authority.
     * AccessPoint: Active SSID, BSSID, IP
     */
    io.imqa.core.network.AccessPoint ap = new io.imqa.core.network.AccessPoint();
    ap.setSsid("IMQA");
    ap.setBssid("cc:40:d0:f7:a5:d7");
    ap.setIpAddress("192.168.0.1");
    imqaOption.addWifiLimitList(ap);

    /*
     * Default value : 10
     * Sets the maximum usage of dump data.
     * int : Maximum usage (in MB)
     */
    imqaOption.setDumpSizeMax(10);

    /*
     * Default value : 15
     * Sets the maximum number of behavior analysis data.
     * int: maximum count
     */
    imqaOption.setBehaviorLengthMax(15);

    /*
     * Default value : 'IMQA-ADDITIONAL-KEY'
     * Inputs additional header information when establishing HTTP communication.
     * String: Name of the additional header key
     */
    imqaOption.setAdditionalHeader(true, "MY-HEADER");
    // or
    imqaOption.setAdditionalHeader(true);
    imqaOption.setAdditionalHeaderKey("MY-HEADER");
    
    io.imqa.mpm.IMQAMpmAgent.getInstance()
        .setOption(imqaOption) // Sets the option to decide the MPM operation method.
        .setContext(this, BuildConfig.FLAVOR) // Initializes the application context.
        .setProjectKey("PROJECT_KEY") // Sets the project key of the IMQA MPM client.
        .init() // Initializes the registered options.
```

{% endcode %}

### MPM独立実行 <a href="#injector" id="injector"></a>

特定のTaskでIMQA MPM Injectorを実行することができます。ただし、上記の方法を使用する場合、実行する位置によって正常にコードが挿入されないことがあります。

{% code title="app.gradle" %}

```gradle
// apply plugin: 'io.imqa' // Should be deactivated for independent execution.

// You must manually insert this part because auto-insert function is canceled.
dependencies {
       implementation 'io.imqa:imqa-core:2.27.5'
       implementation 'io.imqa:imqa-mpm-client:2.27.9'
       implementation 'io.imqa:imqa-crash-client:2.27.5'
 }

// Creates with a constructor because it is a plugin object (uses static internally.)
io.imqa.IMQAPlugin imqaPlugin = new io.imqa.IMQAPlugin()
// Sets basic IMQA options (IMQAOption, BuildOption, imqa-service.json.)
imqaPlugin.init(project)

// Creates with a constructor because it is an action object (uses static internally.)
// Reflects IMQA options in app.gradle. Reflects the basic information of the development environment (build tool, variants, etc.). Inserts IMQA dependency automatically.
new io.imqa.injector.GJavacAction(project.name).setConfiguration(project)

android.applicationVariants.all { variant ->
    // A variable name must be inserted into doLast Lamda when setting.
    // If the variable name is not specified, an error occurs because the built-in gradle “task” is called.
    variant.javaCompile.doLast { task ->
        // Executes CompileAction at the current location based on the above settings.

        // If there are Kotlin codes in the project, add the codes below:
        new io.imqa.injector.CompileAction(
                io.imqa.injector.util.BuildOption.BUILD_LOCATION_TYPE.kotlin,
                project.name,
                io.imqa.injector.GJavacAction.convertBuildType(variant.getBuildType()),
                io.imqa.injector.GJavacAction.makeFlavor(variant.getBuildType().name,   variant)
            )
            .execute(task)

        // Gradle 3.2 ~ 3.4, 4.0, 4.1 :  io.imqa.injector.util.BuildOption.BUILD_LOCATION_TYPE.javacCompileClasses

       // Gradle 3.5 and later  io.imqa.injector.util.BuildOption.BUILD_LOCATION_TYPE.javacClasses

       // Other versions: io.imqa.injector.util.BuildOption.BUILD_LOCATION_TYPE.classes

        new io.imqa.injector.CompileAction(
                io.imqa.injector.util.BuildOption.BUILD_LOCATION_TYPE.javacCompileClasses,
                project.name,
                io.imqa.injector.GJavacAction.convertBuildType(variant.getBuildType()),
                io.imqa.injector.GJavacAction.makeFlavor(variant.getBuildType().name,   variant)
            )
            .execute(task)
    }
}
```

{% endcode %}

## 2. ネットワーク収集設定

IMQA MPMフレームワークでは、ネットワーク収集について自動的に測定しますが、特定のライブラリの場合は手動で設定を進める必要があります。

### AsyncHttpClient対応&#x20;

AsyncHttpClient対応 AsyncHttpClientライブラリを使用して、ネットワーク要求に応じて次のように追加します。

{% code title="MainActivity.java" %}

```javascript
...
AsyncHttpClient client = new AsyncHttpClient();
...
HttpData httpData = new HttpData();
client.get(this, url, new AsyncHttpResponseHandler() {
    @Override
    public void onStart() {
       // Enter network request information
        URI uri = this.getRequestURI();
        httpData.setHostName(uri.getHost());
        httpData.setMethod("get"); // get | post 
        httpData.setProtocol(uri.getScheme());
        httpData.setPathName(uri.getPath());
    }
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
          // Enter network response code ( if successful ) 
           httpData.setStatus(statusCode + "");
    }
    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
          // Enter network response code ( if failure ) 
        httpData.setStatus(statusCode + "");
    }
    @Override
    public void onFinish() {
        // Network collection progress ( Upon completion of request ) 
        httpData.setEndTime(System.currentTimeMillis());
        HttpCollector.collect(httpData);
    }
});

...
```

{% endcode %}

## &#x20;<a href="#proguard" id="proguard"></a>

## 3. ProGuard設定 <a href="#proguard" id="proguard"></a>

ProGuardは、使用しないリソースを削除してクラスやメソッドの名前を短く短縮するなど、APKを最大限小さくするためのツールです。ProGuardまたはDexGuardを使用する場合は、以下の内容を参考にしてください。マッピングファイルをアップロードすると、原本クラス・メソッド名をクラッシュレポートに表示することができます。

### 事前準備 <a href="#preparation" id="preparation"></a>

開発中のプロジェクトでProguardを使用する場合、ソースコードが難読化され解析が困難になります。このとき、作成されるmapping.txtファイルを利用すると、難読化されたコードを解析することができるようになります。

Proguardルール(proguard-rules.pro)に以下の内容を追加してください。

{% code title=" proguard-rules.pro" %}

```
 -keepattributes SourceFile,LineNumberTable
 -printmapping map.txt

 # IMQA Proguard
 -keep class io.imqa.** { *; }
 -dontwarn io.imqa.**

 # okhttp3 Proguard
 -dontwarn okhttp3.**
 -dontwarn okio.**oj
```

{% endcode %}

app/build/outputs/mapping/debug(またはrelease)/mapping.txtの位置にファイルが作成されます。(buildTypeとflavorによってファイルの位置は多少異なることがあります。)\
このように作成されたファイルを、<http://crash.imqa.io>にアクセスしてアップロードしてください。

{% hint style="warning" %}
Androidの場合、「mapping.txt」、「map.txt」などの「txt」ファイルをアップロードします。
{% endhint %}

### アップロード手順 <a href="#upload" id="upload"></a>

1\. プロジェクトメニューから設定へ移動します。

<figure><img src="https://lh7-us.googleusercontent.com/gu6L1SJiDWyYrdcW4bKLdqi0Z4N6UCis17lhNoaXd21D3PUMoruigJxzSTokdrAsXzU4BpxP9R_qQJBuvzi4o9Cb19OdJ8NSVCUom21zgAsD2JyEbSFcb-GfcjfCQlVxlKFuMO_EM_aYMVQRgtt8tQ" alt=""><figcaption></figcaption></figure>

2\. \[ファイル選択]ボタンを押してアップロードウィンドウを開いてください。

<figure><img src="https://lh7-us.googleusercontent.com/GG8hCZww4p3LklmV9AV0NWRcDaPlVrZfPwWYSJuBGPuGVcFfSQOSdqnUni1_GotUXzFbyBvh_EmKCqBIjwaQNtgIiFTy5522nt_j9-oqXFMJQZhzrbr5AwB9zT7CvEnriOkCwe6tqxENStUf5qQlLw" alt=""><figcaption></figcaption></figure>

3\. Gradleに明示されたApp versionに適した\[ファイル選択]ボタンを押してmapping.txtファイルをアップロードしてください。

<figure><img src="https://lh7-us.googleusercontent.com/CR3K90eMDvFjf80qkjGqnpZ3QV5gQQuPsfRuYX85ekr7D59ctGb_f0S6dy9SGHHQPycmoplsRepISbbT52ac76vOhjXAsJw388ByFhlhbLMzm0itbPoBSjjnwJhPLZgS8F0kEKj7Ni6gs7gUI2bvOw" alt=""><figcaption></figcaption></figure>

4\. \[登録]ボタンを押すと、以後アップロードされるクラッシュ情報は解析されて表示されます。

{% hint style="warning" %}
アプリの最新バージョンがリリースされた場合、該当するバージョンで発生したクラッシュ情報を確認するためには同じアプリバージョンのマッピングファイルを追加登録してください。
{% endhint %}

## 4. MPM Webviewガイド <a href="#mpm-webview-guide" id="mpm-webview-guide"></a>

### WebView HTTPのリクエスト <a href="#webview-http" id="webview-http"></a>

#### Web Serverの設定 <a href="#web-server" id="web-server"></a>

WebViewデータを収集するときは、WebViewを提供するWebページにIMQA Webview Javascriptライブラリを挿入する必要があります。必要に応じてファイルをダウンロードし、Webサーバーから直接提供することができます。

(クロスオリジン問題が発生したとき、直接importして使うことをお勧めします。)

{% hint style="info" %}
MPM / WPM統合を使用する場合のエージェントのインストール方法は、「IMQA WPM / WCRashインストールガイド> 1.2。 WPM / MPM統合の使用（WebAgent + WebviewAgentのインストール）」を参照してください。
{% endhint %}

{% code title="Inserting a WebView file" %}

```javascript
<!-- IMQA Webview Agent(1.1.3バージョン以下)です。 -->
<script type="text/javascript" src="https://cdn.imqa.io/agent/webview-agent-1.1.2.js"
crossorigin></script>

<!-- minファイルを適用したい場合: -->
<script type="text/javascript" src="https://cdn.imqa.io/agent/webview-agent-1.1.2.min.js"
crossorigin></script>
```

{% endcode %}

```html
<!-- IMQA Webview Agent(1.1.3バージョン以上)です。  -->
<script type="text/javascript" src="https://cdn.imqa.io/agent/webview-agent-1.1.3.js"
crossorigin></script>

<script>
    ((w, c, _wv, _w, _wk, _mh, _b) => {        
       w[_wv](w); // WebViewエージェント実行関数
    })(window, 'imqaClientConfig', 'IMQAWebviewMain', 'IMQAWebMain', 'webkit', 'messageHandlers', 'ImqaBridge')
</script>
```

#### Android Agentを設定 <a href="#android-agent" id="android-agent"></a>

MPMは、WebViewに関するページやリクエストを収集します。収集するためには、Option設定とMPMWebviewInterfaceを追加する必要があります。また、WebViewで発生したエラー情報を収集することもできます。 Webview Crash 収集のためには CrashWebviewBridge を追加する必要があります。

{% code title="MyWebViewActivity.java" %}

```java
...
public void onCreate() {
    WebView webView = (WebView) findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true); // Javascript Enable

    // Insert WebView interface (ImqaBridge required)
    io.imqa.mpm.network.webview.WebviewInterface imqaJavascript = 
        new io.imqa.mpm.network.webview.WebviewInterface();

    // Additional setup code (Webview Agent (ver. 1.1.2 later) WebView Crash Collection)
    imqaJavascript.setSendErrorBridge(new io.imqa.crash.webview.CrashWebviewBridge(this));

    webView.addJavascriptInterface(imqaJavascript, "ImqaBridge");
    ...
    }
...
```

{% endcode %}

{% code title="MyWebViewActivity.kt" %}

```kotlin
...
public void onCreate() {
    // IMQA settings section
    val webview:WebView = findViewById(R.id.webview_sample)
    webview.settings.javaScriptEnabled = true; // Javascript Enable

    // Insert WebView interface (ImqaBridge required)
    val imqaJavascriptInterface:io.imqa.mpm.network.webview.WebviewInterface = io.imqa.mpm.network.webview.WebviewInterface();

    // Additional setup code (Webview Agent (ver. 1.1.2 later) WebView Crash Collection)
    imqaJavascriptInterface.setSendErrorBridge(CrashWebviewBridge(this))

    webview.addJavascriptInterface(imqaJavascriptInterface,"ImqaBridge")	
    ...
    }
...  
```

{% endcode %}

## **5.** MPM HTTPS ガイド <a href="#mpm-https-guide" id="mpm-https-guide"></a>

### HttpsURLConnection対応 <a href="#url-connection" id="url-connection"></a>

IMQA Clientは、HttpsURLConnectionベースのネットワーク要求を収集できます。 HttpsURLConnectionベースのネットワーク要求の場合は、次のように追加してください。

#### **HttpsURLConnection** <a href="#connection" id="connection"></a>

{% code title="MainActivity.java" %}

```java
...
// Wraps the HttpsURLConnection object with ConnectionWrapper.
URL url = new URL("https://some.host.com");
HttpsURLConnection conn = (HttpsURLConnection) ConnectionWrapper.wrap((HttpsURLConnection) url.openConnection());
...
```

{% endcode %}

{% code title="MainActivity.kt" %}

```java
...
// HttpsURLConnection 객체를 ConnectionWrapper 로 감쌈
var url : URL = URL("https://some.host.com")
var conn : HttpsURLConnection = 
    ConnectionWrapper.wrap(
        url.openConnection() as HttpsURLConnection
    ) as HttpsURLConnection
...
```

{% endcode %}

### **OkHttp**対応 <a href="#okhttp" id="okhttp"></a>

IMQA ClientはOkHttpベースのネットワーク要求を収集できます。 OkHttpベースのネットワーク要求の場合は、次のように追加してください。

#### **OkHttp Client** <a href="#okhttp-client" id="okhttp-client"></a>

**1. OkHttp3**

{% code title="MainActivity.java" %}

```java
...
// Add MPMInterceptor to OkHttpClient
OkHttpClient client = new OkHttpClient.Builder()
    .addNetworkInterceptor(new MPMInterceptor())
    .build();
...

// Run OkHttpClient with the added interceptor
Response response = client.newCall(request).execute();
...
```

{% endcode %}

{% code title="MainActivity.kt" %}

```java
...
// Add MPMInterceptor to OkHttpClient
val builder : OkHttpClient.Builder = OkHttpClient.Builder()
val client : OkHttpClient = IMQAManager.wrapOkhttp(builder)
    .addNetworkInterceptor(MPMInterceptor())
    .build();
...

// Run OkHttpClient with the added interceptor.
val response : Response = client.newCall(request).execute()
...
```

{% endcode %}

**2. Retrofit 2.0**

{% code title="MainActivity.java" %}

```java
...
// Add MPMInterceptor to OkHttpClient
OkHttpClient client = new OkHttpClient.Builder()
    .addNetworkInterceptor(new MPMInterceptor())
    .build();
...

new Retrofit.Builder()
    .baseUrl(host)
    .client(client) // Use OkHttpClient with the added interceptor
    .build();
...
```

{% endcode %}

{% code title="MainActivity.kt" %}

```java
...
// Add MPMInterceptor to OkHttpClient
val builder : OkHttpClient.Builder = OkHttpClient.Builder()
val client : OkHttpClient = IMQAManager.wrapOkhttp(builder)
    .addNetworkInterceptor(MPMInterceptor())
    .build();
...

val retrofit = Retrofit.Builder()
    .baseUrl(host)
    .client(client) // Use OkHttpClient with the added interceptor
    .build()
...
```

{% endcode %}

#### イメージロードライブラリ対応 <a href="#image-loading" id="image-loading"></a>

**1. Picasso**

picasso の場合、okhttp を使用する場合はデフォルトの downloader として okhttp を選択します。 この downloader にアンタセプターを追加するために以下のように追加してくれます。 まず、OkHttp3Downloader依存関係を追加します。

```css
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
```

{% code title="MainActivity.java" %}

```java
// The downloader that MPMInterceptor is added in advance should be inserted before initializing Picasso's Singleton instance.
Picasso.setSingletonInstance(
    new Picasso.Builder(this)
            .downloader(new OkHttp3Downloader(
                    new OkHttpClient.Builder()
                            .addInterceptor(new MPMInterceptor())
                            .build()
            )).build());
```

{% endcode %}

**2. Glide**

Glideの場合、HttpUrlConnectionをデフォルトのhttpライブラリとして使用します。 okhttpを使用したい場合は、OkHttpClientをregistryに設定してください。

```java
compile "com.github.bumptech.glide:okhttp3-integration:4.8.0"
```

{% code title="MainActivity.java" %}

```java
@GlideModule
public class MyAppGlideModule extends AppGlideModule {

    @Override
    public void registerComponents(Context context, Glide glide, Registry registry) {
        super.registerComponents(context, glide, registry);
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(new MPMInterceptor())
                .build();
        registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(client));
    }
    ...
}
```

{% endcode %}

### **HttpClient**対応 <a href="#http-client" id="http-client"></a>

IMQA Clientは、HttpClientベースのネットワーク要求を収集できます。 HttpClientベースのネットワーク要求の場合は、次のように追加してください。

#### **HttpClient**

**1. HttpClient (org.apache.http.legacy)**

{% code title="MainActivity.java" %}

```java
...
// dd HttpClientInterceptor to DefaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpClientInterceptor.setIMQAInterceptor(httpClient);
...
```

{% endcode %}

{% code title="MainActivity.kt" %}

```java
...
// Add HttpClientInterceptor to DefaultHttpClient
val httpClient : DefaultHttpClient = DefaultHttpClient()
HttpClientInterceptor.setIMQAInterceptor(httpClient)
...
```

{% endcode %}

**2. HttpClient (cz.msebera.android.httpclient)**

{% code title="MainActivity.java" %}

```java
...
// Add OldHttpClientInterceptor to DefaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
OldHttpClientInterceptor.setIMQAInterceptor(httpClient);
...
```

{% endcode %}

{% code title="MainActivity.kt" %}

```java
...
// Add HttpClientInterceptor to DefaultHttpClient
val httpClient : DefaultHttpClient = DefaultHttpClient()
OldHttpClientInterceptor.setIMQAInterceptor(httpClient)
...
```

{% endcode %}

### **Volley**対応 <a href="#volley" id="volley"></a>

IMQA Clientは、Volleyベースのネットワーク要求を収集できます。 Volleyベースのネットワーク要求の場合は、次のように追加してください。

#### **Volley**

**1. Volley (com.android.volley)**

{% code title="MainActivity.java" %}

```java
...


StringRequest request = new StringRequest(
   ....
)

// Add IMQAHurlStack to RequestQueue
RequestQueue requestQueue = Volley.newRequestQueue(this, new IMQAHurlStack());
requestQueue.add(request);
...
```

{% endcode %}

### 現在のバージョンで発生する可能性のある不具合 <a href="#issue" id="issue"></a>

{% hint style="warning" %}
Interceptor機能を手動で挿入する必要があります。 （現在HTTPURLConnection、Okhttp、Retrofit、HttpClient（org.apache、cz.msebera）自動インストールをサポートしています。）
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.imqa.io/imqa-guide/jpn/installation/android/mpm-sdk-setting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
