网络请求 return 空 - Android

Network Requests return null - Android

我正在 android 从事网络通信项目,但我的应用程序无法运行!经过一些调试,我发现每个网络请求都有来自系统的空响应。

我尝试了很多方法,例如: 1) 硬重启我的 phone 2) 将所有网络权限添加到清单文件

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

3) 使用本地网络(我的 phone 作为服务器) 4) 让所有应用程序连接到网络:设置 > 联网应用程序 > ...

但是!什么都没发生...

这是我的类似问题link,但是这个话题没有答案: can't connect to internet in ONLY in my android app. Each method to connect internet returns null

网络在我的 phone 上运行正常,因为电报和 chrome 等一些应用运行良好!

这里有一件有趣的事情,当我将这段代码复制并粘贴到简单的 java 项目而不是 android 项目时,它运行良好!

因为我想找出问题出在哪里,所以我只是复制了3行简单的代码到简单的android项目中,但仍然没有任何反应!

清单文件:

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

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

源文件

package com.example.dltests;

import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        TextView mTextView = (TextView) findViewById(R.id.hello);

        try 
        {
            URL mUrl = new URL("http://192.168.1.53:8080/some.zip");
            HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
            mTextView.setText(mHttpURLConnection.getContentLength());

        } 
        catch (Exception e) 
        {
            mTextView.setText("ERROR: " + e.getMessage());
        }

    }
}

结果是: 错误:空

Android 禁止您在 UI 线程中联网。你需要做什么它产生一个单独的线程来为你做网络。然后你需要一个接收器或处理程序来 post/update 和 UI 数据。

1 - 创建一个新的 class:

import android.os.Handler;
import android.os.Message;

public class GetData extends Thread
{

    // Holds url that data is stored on
    private URL url

    // Sets the url value
    public GetData(URL newUrl)
    {
         url = newUrl;
    }

    // Runs when the thread is launched
    public void run()
    {
        // Opens connection
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        // Sends back to UI using a Message
        Message msg = MainActivity.MainActivityInterface.obtainMessage(MainActivity.getAndUpdate);
        msg.obj = con.getContentLength(); // Adds the data
        HomeScreen.homeScreenInterface.sendMessage(msg); 
    }
}

2 - 在 activity 中创建处理程序,以便可以更新 UI 以及启动工作线程

import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import android.os.Handler;
import android.os.Message;

public class MainActivity extends Activity {

    // Holds activity instance
    public static MainActivity currentInstance;

    // Variable that allows us to separate messages for handler
    public static final getAndUpdate = 0;

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

        currentInstance = this;
        TextView mTextView = (TextView) findViewById(R.id.hello);

        try 
        {
            URL mUrl = new URL("http://192.168.1.53:8080/some.zip");

            // Spawns worker thread
            GetData gd = new GetData(mUrl);
            gd.start();
        } 
        catch (Exception e) 
        {
            mTextView.setText("ERROR: " + e.getMessage());
        }
    }

    // Deals with service responses
    public static Handler MainActivityInterface = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch(msg.what)
            {
                case getAndUpdate:
                    currentInstance.mTextView.setText((String) msg.obj); // Gets message object and updates UI
                break;
            }
        }
    }
}

希望对您有所帮助。请注意,我还没有测试它,因为我离编码计算机很远!