简体   繁体   中英

How can I make my android app connect to the internet? (Unity)

I'm doing an Android application that request info from a website (I already made the website) and displays it on the screen.

I have this code to do that:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Android;
using UnityEngine.Networking;
using UnityEngine.UI;

public class WebTextLoader : MonoBehaviour
{
    // Start is called before the first frame update
    [Serializable]
    public class PlaceInfo
    {
        public string Titulo = "";
        public string Texto = "";
    }

    public string URL;
    public Text TituloUI;
    public Text TextoUI;

    public PlaceInfo placeInfo;



    public void Start()
    {
        if (Debug.isDebugBuild)
        {
            StartCoroutine(GetRequest(URL));

        }
    }
    IEnumerator GetRequest(string uri)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();

            string jsonForm = uri;

            if (webRequest.isNetworkError)
            {
                Debug.Log("Error loading");

            }
            else
            {
                try
                {
                    placeInfo = JsonUtility.FromJson<PlaceInfo>(webRequest.downloadHandler.text);
                    TituloUI.text = placeInfo.Titulo;
                    TextoUI.text = placeInfo.Texto;

                }
                catch
                {
                    Debug.Log("Error in connection");
                }
            }

        }
    }
}

And this is how the component looks:

picture of the component

(I already tried changing htttp to https)

Now, when I test it on the Unity editor, it works perfectly, but when I try it on my phone, it doesn't. The text never loads.

I thought it was something about the permissions, so I gave the internet and the access_network_state, still didn't work (I also have the internet on require in the player settings)

I'm missing something?

In order to perform network operations in your application, your manifest must include the following permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM