Unity Wifi・キャリア電波レベルの取得（Android）


■Unity側（WIFIはUnity側だけで完結）

```
using UnityEngine;

/// <summary>
/// 電波状態の取得クラス（WIFI/キャリア）
/// </summary>
public static class NetworkStatus
{
    /// <summary>
    /// 電波強度MAX値
    /// </summary>
    public const int MAX_SIGANAL_STRENGTH = 4;

#if !UNITY_EDITOR && UNITY_ANDROID
    private static AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    private static AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
#endif

    /// <summary>
    /// 通信状態を取得
    /// </summary>
    /// <returns></returns>
    public static bool CanUseNetwork
    {
        get
        {
            // 通信可能ならTrue
            return Application.internetReachability != NetworkReachability.NotReachable;
        }
    }

    /// <summary>
    /// 通信状況を取得
    /// </summary>
    public static int Level
    {
        get
        {
            int level = 0;
            switch(Application.internetReachability)
            {
                // WIFI接続可能
                case NetworkReachability.ReachableViaLocalAreaNetwork:
                    level = WifiLevel;
                    break;
                // LTE/3G接続可能
                case NetworkReachability.ReachableViaCarrierDataNetwork:
                    //level = CarrierLevel;
                    break;
                default:
                    level = 0;
                    break;
            }
            return level;

        }
    }

    /// <summary>
    /// Wifiの電波レベルを取得して返す
    /// </summary>
    /// <returns></returns>
    private static int WifiLevel
    {
        get
        {
#if !UNITY_EDITOR && UNITY_ANDROID
            var wifiManager = currentActivity.Call<AndroidJavaObject>("getSystemService", "wifi");
            int rssi = wifiManager.Call<AndroidJavaObject>("getConnectionInfo").Call<int>("getRssi");
            return wifiManager.CallStatic<int>("calculateSignalLevel",rssi,5);
#endif
            return MAX_SIGANAL_STRENGTH;

        }
    }

}
```



## キャリアのレベル取得用クラス（GetCarrier.java）

```
package jp.co.test.mobilestate;


import android.telephony.CellInfo;
import android.content.Context;
import android.os.Bundle;
import android.telephony.CellInfoCdma;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.util.List;
import com.unity3d.player.UnityPlayerActivity;
import static com.unity3d.player.UnityPlayer.UnitySendMessage;


public class GetCarrier extends UnityPlayerActivity  {

    TelephonyManager telephonyManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d("TM", "onCreate");

        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    }

    @Override
    public void onResume()
    {
        super.onResume();

        Log.d("TM", "onResume");
        telephonyManager.listen(phoneState, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS | PhoneStateListener.LISTEN_CELL_LOCATION);

    }

    @Override
    public void onPause()
    {
        super.onPause();

        telephonyManager.listen(phoneState, PhoneStateListener.LISTEN_NONE);
        Log.d("TM", "onPause");
    }

    /**
     * 電波強度の変更を検出するListner
     */
    public PhoneStateListener phoneState;
    {
        phoneState = new PhoneStateListener() {
            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {

                Log.d("TM", "PhoneStateListener");

                List<CellInfo> cellInfoList;
                int cellSig,  cellLv = 0;

                try {
                    cellInfoList = telephonyManager.getAllCellInfo();
                    for (CellInfo cellInfo : cellInfoList)
                    {
                        if (cellInfo instanceof CellInfoLte)
                        {
                            Log.d("TM", "CellInfoLte");
                            // cast to CellInfoLte and call all the CellInfoLte methods you need
                            // gets RSRP cell signal strength:
                            cellSig = ((CellInfoLte) cellInfo).getCellSignalStrength().getDbm();

                            Log.d("TM", "cellSig=" + String.valueOf(cellSig));
                            // Gets the LTE TAC: (returns 16-bit Tracking Area Code, Integer.MAX_VALUE if unknown)
                            cellLv = ((CellInfoLte) cellInfo).getCellSignalStrength().getLevel();
                            Log.d("TM", "cellLv=" + String.valueOf(cellLv));

                            UnitySendMessage("GetSignal","onCallBack","CellInfoLte cellLv=" + String.valueOf(cellLv) + " getDbm=" + String.valueOf(cellSig));
                        }
                        if (cellInfo instanceof CellInfoGsm)
                        {
                            Log.d("TM", "CellInfoGsm");

                            cellSig = ((CellInfoGsm) cellInfo).getCellSignalStrength().getDbm();
                            Log.d("TM", "getDbm=" + String.valueOf(cellSig));

                            // Gets the LTE TAC: (returns 16-bit Tracking Area Code, Integer.MAX_VALUE if unknown)
                            cellLv = ((CellInfoGsm) cellInfo).getCellSignalStrength().getLevel();
                            Log.d("TM", "cellLv=" + String.valueOf(cellLv));
                            UnitySendMessage("GetSignal","onCallBack","CellInfoGsm cellLv=" + String.valueOf(cellLv) + " getDbm=" + String.valueOf(cellSig));
                        }

                        if (cellInfo instanceof CellInfoCdma)
                        {
                            Log.d("TM", "CellInfoCdma");

                            cellSig = ((CellInfoCdma) cellInfo).getCellSignalStrength().getDbm();
                            Log.d("TM", "getDbm=" + String.valueOf(cellSig));

                            // Gets the LTE TAC: (returns 16-bit Tracking Area Code, Integer.MAX_VALUE if unknown)
                            cellLv = ((CellInfoCdma) cellInfo).getCellSignalStrength().getLevel();
                            Log.d("TM", "cellLv=" + String.valueOf(cellLv));

                            UnitySendMessage("GetSignal","onCallBack","CellInfoCdma cellLv=" + String.valueOf(cellLv) + " getDbm=" + String.valueOf(cellSig));
                        }
                    }
                } catch (Exception e) {
                    Log.d("SignalStrength", "+++++++++++++++++++++++++++++++ null array spot 3: " + e);
                }

                super.onSignalStrengthsChanged(signalStrength);
            }

        };
    }
}

```


## build.gradle
```
apply plugin: 'com.android.library'

android {
    compileSdkVersion 28



    defaultConfig {
        minSdkVersion 17
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar','*.aar'], exclude: ['classes.jar'])
    compileOnly fileTree(dir: 'libs', include: ['classes.jar'])
}

```

■class.jarをAndroidstudioの指定のlibsフォルダの下に置く

下記パスにある

C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\il2cpp\Release\Classes

or

C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\il2cpp\Development\Classes

■aarの作り方

●赤丸のSyncをしてから
　gradleビューを開き、assebleRelease を実行

![gradle.png](https://qiita-image-store.s3.amazonaws.com/0/17904/686c69dc-6e5a-bbe3-fecc-6794a9cd3759.png)


■UnitySendMessage

第1引数はゲームオブジェクト名です、
ヒエラルキーにある名前と一致しないとダメ

ずっとクラス名だと思って地味にはまる。