Android Studio无法访问互联网。

huangapple go评论101阅读模式
英文:

Android Studio no access to internet

问题

Here's the translation of your provided content:

我的应用程序可以访问一个简单的JSON并在模拟器(PIXEL 2 API 24)上正常运行,但在我连接的任何实际设备上都无法运行。已尝试使用S8和Note10,两者都没有启用数据节省模式。

甚至在之后检查了应用程序的数据使用情况,显示为"0 B"。

以下是文件:

MainActivity.java:

package com.example.internettest;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView textView;
    ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        textView = (TextView) findViewById(R.id.textView);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JsonTask().execute("http://46d30cf268b0.ngrok.io/LEATest/");
            }
        });
    }

    private class JsonTask extends AsyncTask<String, String, String> {
        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected String doInBackground(String... params) {
            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();
                String line = "";

                while ((line = reader.readLine()) != null) {
                    buffer.append(line + "\n");
                    Log.d("Response: ", "> " + line);   //在这里可以获取整个响应内容...
                }

                return buffer.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Toast toast = Toast.makeText(getApplicationContext(),
                    "Before Try = |" + result + "|",
                    Toast.LENGTH_SHORT);

            toast.show();

            textView.setText(result);
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.internettest">

    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是在模拟器上按下按钮后的结果(所有用户名/密码都是虚假的):Android Studio无法访问互联网。

英文:

My app to access a simple JSON and display it runs perfectly fine on the emulator(PIXEL 2 API 24) but not on any actual device I connect to it. Tried with both S8 and Note10, neither have data saver on either.

I even checked the apps data use afterwards and it said "0 B".

Here are the files:

MainActivity.java:

package com.example.internettest;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JsonTask().execute(&quot;http://46d30cf268b0.ngrok.io/LEATest/&quot;);
}
});
}
private class JsonTask extends AsyncTask&lt;String, String, String&gt; {
protected void onPreExecute() {
super.onPreExecute();
//pd = new ProgressDialog(MainActivity.this);
//pd.setMessage(&quot;Please wait&quot;);
//pd.setCancelable(false);
//pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = &quot;&quot;;
while ((line = reader.readLine()) != null) {
buffer.append(line+&quot;\n&quot;);
Log.d(&quot;Response: &quot;, &quot;&gt; &quot; + line);   //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//if (pd.isShowing()){
//    pd.dismiss();
//}
Toast toast = Toast.makeText(getApplicationContext(),
&quot;Before Try = |&quot; + result + &quot;|&quot;,
Toast.LENGTH_SHORT);
toast.show();
textView.setText(result);
}
}
}

AndroidManifest.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
package=&quot;com.example.internettest&quot;&gt;
&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
&lt;application
android:allowBackup=&quot;true&quot;
android:icon=&quot;@mipmap/ic_launcher&quot;
android:label=&quot;@string/app_name&quot;
android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
android:supportsRtl=&quot;true&quot;
android:theme=&quot;@style/AppTheme&quot;&gt;
&lt;activity android:name=&quot;.MainActivity&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;/application&gt;
&lt;/manifest&gt;

Here's the result of pressing the button on the emulator(all fake username/passwords):
Android Studio无法访问互联网。

答案1

得分: 1

执行JsonTask的方式如下 -

new JsonTask().execute("https://46d30cf268b0.ngrok.io/LEATest/");

如@isthemartin建议的那样,当您在实际设备(S8和Note10)上运行您的应用程序时,流量被阻止,因为不允许HTTP连接。

您可以添加android:usesCleartextTraffic="true",但这样您的应用程序将允许非安全的HTTP连接。

我尝试了您的API URL(https://46d30cf268b0.ngrok.io/LEATest/)响应请求,所以,为什么不在不在您的应用程序中创建安全漏洞的情况下直接使用它呢?

英文:

Execure your JsonTask as follows -

new JsonTask().execute(&quot;https://46d30cf268b0.ngrok.io/LEATest/&quot;);

As suggested by @isthemartin, when you are running you app in actual device (S8 and Note10) the traffic is getting block because HTTP connection is not allowed.

Either you can add android:usesCleartextTraffic=&quot;true&quot; but then you app will allow non secure HTTP connections.

I tried your API URL (https://46d30cf268b0.ngrok.io/LEATest/) is responding to the request so, why don't simply use it without making a security gap in your app.

答案2

得分: 0

你的实际设备可能会阻止HTTP连接,所以在这种情况下,你需要启用这些连接,请查看此帖子

英文:

probably your actual devices are blocking http connections, so in this case you need to enable those connections, check this post

答案3

得分: 0

请将以下代码添加到您的 AndroidManifest.xml 文件中:

android:usesCleartextTraffic="true"

这样代码会变成这样:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.internettest">

    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
英文:

Please add this code to your AndroidManifest.xml file.

   android:usesCleartextTraffic=&quot;true&quot;

so the code can be like this :

 &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
package=&quot;com.example.internettest&quot;&gt;
&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
&lt;application
android:allowBackup=&quot;true&quot;
android:icon=&quot;@mipmap/ic_launcher&quot;
android:label=&quot;@string/app_name&quot;
android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
android:supportsRtl=&quot;true&quot;
android:usesCleartextTraffic=&quot;true&quot;
android:theme=&quot;@style/AppTheme&quot;&gt;
&lt;activity android:name=&quot;.MainActivity&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;/application&gt;

</manifest>

huangapple
  • 本文由 发表于 2020年8月1日 05:50:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63199525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定