0

所以Android不允许网络操作在主线程上运行,这很公平。我在另一个线程上运行此代码时遇到了一些麻烦。你能看看我的代码,看看这是否可行/正确吗?谢谢您,感谢您提供的任何帮助。

public class StartActivity extends Activity implements Runnable {
    public static final int timeout = 3000;
    private boolean boolConStatus = false;

    public static final String TAG = "StartActivity";
    public static final String url = "serverIP";

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        Log.d(TAG, "onCreated with Bundle: " + bundle);
        setContentView(R.layout.activity_start);
    }

    public void run() {
        boolean boolConStatus; 
        boolConStatus = this.isConnected();
        toaster();
    }

    public boolean getConStatus() {
        return boolConStatus;
    }


    public void toaster() {
                boolConStatus = this.isConnected();
                if (boolConStatus == true) {
                    Toast.makeText(getApplicationContext(),
                            "Connected to Server", Toast.LENGTH_LONG);
                } else {
                    Toast.makeText(getApplicationContext(),
                            "All has failed", Toast.LENGTH_LONG);
                }
}
        public boolean isConnected() {
            try {
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo ni = cm.getActiveNetworkInfo();

                if (ni != null && ni.isConnected()) {
                    URL server = new URL(url);
                    HttpURLConnection huc = (HttpURLConnection) server.openConnection();
                    huc.setRequestProperty("Connection", "close");
                    huc.setConnectTimeout(timeout);
                    huc.connect();

                    if (huc.getResponseCode() == 200) {
                        return true;
                    } else {
                        Log.d("NOT CONNECTED TO SERVER", "NOT CONNECTED TO SERVER");
                        return false;
                    }
                } else {
                    Log.d("NO INTERNET CONNECTION", "NO INTERNET CONNECTION");
                    return false;
                }
                } catch (Exception e) {
                    Log.d(TAG, e.getLocalizedMessage(), e);
                e.printStackTrace();
            }
            return false;
        }
    }
4

1 回答 1

1

没有线程,Runnable 本身就什么都不是。尝试将此添加到您的 onCreate() 或 onResume() 中:

 new Thread(this).start();

然后可能必须阅读此https://developer.android.com/reference/java/lang/Thread.html以便您知道应该如何做......在你的情况下,也许AsyncTask的使用是合适的...... .但是您必须首先了解线程的工作原理。

于 2013-01-05T18:43:44.120 回答