unity3d 判断url是否正常 android and ios

来源:互联网 发布:女排比赛直播软件 编辑:程序博客网 时间:2024/06/06 02:32

先说明一下unity可以用www的判断一个url 是否可用,但有很大的问题,其一是判断结果不准确,其二是会引起线程阻塞,卡死,总之一句话就是一个坑。坑。坑所有,我们选择了用java 和oc 来进行判断 废话不多上代码

调用

//1: 判断的URL,2超时时间,3回调        InetAddress.Instance.CheckInetAddressReachableAsync("http://blog.csdn.net/qqo_aa/", 3000, (address, isReachable, errorMsgInetAddress) =>        {            //这是干神马        });

C#

    public void CheckInetAddressReachableAsync(string address, int timeoutInMS, Action<string, bool, string> callback)    {#if (UNITY_ANDROID && !UNITY_EDITOR) || ANDROID_CODE_VIEW        try        {            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");            AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");            AndroidJavaClass unityPluginLoader = new AndroidJavaClass("java类全名");            unityPluginLoader.CallStatic("CheckInetAddressReachableAsync", currentActivity, address, timeoutInMS, sdkCallback.GetHostName(), sdkCallback.GetMethodName());        }        catch (Exception e)        {        }#elif (UNITY_IOS && !UNITY_EDITOR) || IOS_CODE_VIEW        _IOS_CheckInetAddressReachableAsync(address, timeoutInMS, sdkCallback.GetHostName(), sdkCallback.GetMethodName());#endif    }

android

    public static void CheckInetAddressReachableAsync(Context context, String address, int timeout,            String gameObjectName, String methodName) {        if (address == null || address.isEmpty()) {            return;        }        if (gameObjectName == null || gameObjectName.isEmpty()) {            return;        }        if (methodName == null || methodName.isEmpty()) {            return;        }        InetAddressChecker checker = new InetAddressChecker(context, address, timeout);        checker.SetUnityGameObjectName(gameObjectName);        checker.SetUnityGameObjectMethodName(methodName);        checker.check();    }package com.moba.unityplugin;import java.io.IOException;import java.net.HttpURLConnection;import java.net.InetAddress;import java.net.MalformedURLException;import java.net.URL;import java.util.HashMap;import java.util.Map;import com.unity3d.player.UnityPlayer;import android.content.Context;import android.net.ConnectivityManager;import android.net.NetworkInfo;public class InetAddressChecker{    private static final String TAG = "InetAddressChecker";    private Context mContext = null;    private InetAddress mInetAddress = null;    private String mAddress = "";    private int mTimeout = 3000;    private Thread mThread = null;    private String mGameObjectName = "";    private String mGameObjectMethodName = "";    public InetAddressChecker(Context context, String address, int timeout) {        mContext = context;        mAddress = address;        mTimeout = timeout;    }    public void SetUnityGameObjectName(String gameObjectName) {        mGameObjectName = gameObjectName;    }    public void SetUnityGameObjectMethodName(String methodName) {        mGameObjectMethodName = methodName;    }    public void check() {        if (mAddress == null || mAddress.isEmpty()) {            return;        }        if (mThread != null) {            return;        }        mThread = new Thread(){            @Override            public void run() {                try {                    mInetAddress = InetAddress.getByName(mAddress.replace("http://", "").replace("https://", "").replace("/", ""));                    String hostName = mInetAddress.getHostName() + "(" + mInetAddress.getHostAddress() + ")";                    boolean isReachable = mInetAddress.isReachable(mTimeout / 2);                    if (!isReachable) {                        // check in other ways                        isReachable = isOnline();                    }                    if (isReachable) {                    } else {                    }                    OnCheckResult(true, "", isReachable);                } catch (Exception e) {                    OnCheckResult(false, e.toString(), false);                }                mThread = null;            }        };        mThread.start();    }    boolean isOnline() {        try {            ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);            NetworkInfo netInfo = cm.getActiveNetworkInfo();            if (netInfo != null && netInfo.isConnected()) {                try {                    URL url = new URL(mAddress);                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();                    urlc.setConnectTimeout(mTimeout / 2);                    urlc.connect();                    int responseCode = urlc.getResponseCode();                    if (responseCode == HttpURLConnection.HTTP_OK) {                        urlc.disconnect();                        return true;                    }                    urlc.disconnect();                } catch (MalformedURLException e0) {                } catch (IOException e1) {                }            }        } catch (Exception e) {        }        return false;    }    void OnCheckResult(boolean success, String errorMsg, boolean isReachable) {        Map<String, String> parameters = new HashMap<String, String>();        if (mInetAddress != null) {            try {                parameters.put("hostAddress", mInetAddress.getHostAddress());                parameters.put("hostName", mInetAddress.getHostName());            } catch (Exception e) {            }        }        try {            parameters.put("result", success ? "true" : "false");            parameters.put("errorMsg", errorMsg);            parameters.put("isReachable", isReachable ? "true" : "false");        } catch (Exception e) {        }        String msg = "";        try {            JSONObject msgJson = JSONObject.fromObject(parameters);            msg = msgJson.toString();        } catch (Exception e) {            msg = "";        }        if (mGameObjectName != null && !mGameObjectName.isEmpty()) {            if (mGameObjectMethodName != null && !mGameObjectMethodName.isEmpty()) {                UnityPlayer.UnitySendMessage(mGameObjectName, mGameObjectMethodName, msg);            }        }    }}

IOS

  void _IOS_CheckInetAddressReachableAsync(const char *hostName, int timeoutInMS, const char *gameObjectName, const char *gameObjectMethodName)    {        NSString *strGameObjectName = [NSString stringWithUTF8String:gameObjectName];        NSString *strGameObjectMethodName = [NSString stringWithUTF8String:gameObjectMethodName];        NSString *strHostName = [NSString stringWithUTF8String:hostName];        NSURL *url = [NSURL URLWithString:strHostName];        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:(timeoutInMS / 1000.0)];        [NSURLConnection sendAsynchronousRequest:request                                           queue:[NSOperationQueue mainQueue]                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {                                   bool result = true;                                   NSString *errorMsg = @"";                                   bool isReachable = false;                                   if (connectionError != nil) {                                       if (connectionError.localizedDescription != nil) {                                           errorMsg = connectionError.localizedDescription;                                       } else if (connectionError.localizedFailureReason != nil) {                                           errorMsg = connectionError.localizedFailureReason;                                       } else {                                           errorMsg = @"Unhkown Error";                                       }                                   } else {                                       long statusCode = ((NSHTTPURLResponse *)response).statusCode;                                       if (statusCode == 200) {                                           isReachable = true;                                       } else {                                           errorMsg = [NSString stringWithFormat:@"StatusCode: %ld", statusCode];                                       }                                   }                                   NSMutableDictionary *parameters = [[[NSMutableDictionary alloc] initWithCapacity:1] autorelease];                                   [parameters setObject:strHostName forKey:@"hostAddress"];                                   [parameters setObject:strHostName forKey:@"hostName"];                                   [parameters setObject:result ? @"true" : @"false" forKey:@"result"];                                   [parameters setObject:errorMsg forKey:@"errorMsg"];                                   [parameters setObject:isReachable ? @"true" : @"false" forKey:@"isReachable"];                                   NSString* strParameters = [PluginHelper convertToJSONData:parameters];                                   UnitySendMessage("你懂的");                               }];    }
原创粉丝点击