Android线程,这是正确的吗?

时间:2013-01-05 18:33:32

标签: java android multithreading

所以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;
        }
    }

1 个答案:

答案 0 :(得分:1)

如果没有Thread,Runnable本身就没什么。尝试将此添加到onCreate()或onResume():

 new Thread(this).start();

然后可能必须阅读这个https://developer.android.com/reference/java/lang/Thread.html,这样你就知道应该怎么做......在你的情况下,也许AsyncTask的使用是合适的......但你必须先了解如何线程工作。