android.net中的java.net.URL,应用程序立即关闭,新手

时间:2016-08-12 06:59:53

标签: java android networkonmainthread

来自此网址: java.net.URL in android .. newbie question

当我取消注释此行时,我的应用程序开始关闭:

BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));

我的目标是访问网址。我的意思是获取HTML代码,之后我解析它。首先尝试,在获取图像网址成功(未使用的功能中的示例),但对于正常的网址我卡住了。谢谢你的帮助......

我的完整代码:

public class MainActivity extends Activity {

    private ProgressDialog progressDialog;
    private Bitmap bitmap = null;

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        final EditText editTexts = (EditText) findViewById(R.id.editText1);
        editTexts.setOnKeyListener(new EditText.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button 
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) { // Perform action on key press 
                    String name = "Hello " + editTexts.getText();
                    Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
                    TextView t = (TextView) findViewById(R.id.textView1);
                    t.setText(name);
                    if (checkInternetConenction()) {
                        //                          downloadImage("http://www.tutorialspoint.com/green/images/logo.png");
                        //https://postimg.org/image/5bjco36kl/597f512a/
                        //downloadImage("http://s10.postimg.org/5bjco36kl/Quotes_Cover_pic14.png"); // works
                        try {
                            URL url = new URL("http://www.google.com/humans.txt");
                            HttpURLConnection http = (HttpURLConnection) url.openConnection();
                            //int statusCode = http.getResponseCode();
                            String outdata = "";
                            String inputLine;
                            BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));
                            //while ((inputLine = in.readLine()) != null)
                            //    outdata += inputLine;
                            //t.setText(outdata);
                            //in.close();

                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                    //                      if(isOnline())  // works !
                    {
                        //                          Toast.makeText(MainActivity.this, "dalam in kondisi OL ?" , Toast.LENGTH_SHORT).show();
                        //                          t.setText(name+" boolean bro");
                    }
                }
                return false;
            }
        });
        return false;
    }

    public boolean isOnline() {
        ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        Boolean res;
        res = false;
        if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) {

            Toast.makeText(MainActivity.this, "online", Toast.LENGTH_SHORT).show();
            // notify user you are online
            res = true;
        } else if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {

            Toast.makeText(MainActivity.this, "offline", Toast.LENGTH_SHORT).show();
            res = false;
            // notify user you are not online
        }
        return res;
    }


    private boolean checkInternetConenction() {
        //      Toast.makeText(MainActivity.this, "here",   Toast.LENGTH_SHORT).show();

        // get Connectivity Manager object to check connection
        ConnectivityManager connec = (ConnectivityManager) getSystemService(getBaseContext().CONNECTIVITY_SERVICE);


        //        string stat = connec.getNetworkInfo(0).getState();

        //Toast.makeText(MainActivity.this, "stat"+stat,    Toast.LENGTH_SHORT).show();

        // Check for network connections
        if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||

            connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {
            //          Toast.makeText(MainActivity.this, "here1",  Toast.LENGTH_SHORT).show();
            Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
            return true;
        } else if (
            connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {
            //          Toast.makeText(MainActivity.this, "here2",  Toast.LENGTH_SHORT).show();
            Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
            return false;
        }
        //      Toast.makeText(MainActivity.this, "here3",  Toast.LENGTH_SHORT).show();
        return false;
    }

    private void downloadImage(String urlStr) {
        progressDialog = ProgressDialog.show(this, "", "Accessing data from " + urlStr);
        final String url = urlStr;

        new Thread() {
            public void run() {
                InputStream in = null;

                Message msg = Message.obtain();
                msg.what = 1;

                try { in = openHttpConnection(url);
                    // change start here..
                    bitmap = BitmapFactory.decodeStream( in );
                    Bundle b = new Bundle();
                    b.putParcelable("bitmap", bitmap);
                    msg.setData(b); in .close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                messageHandler.sendMessage(msg);
            }
        }.start();
    }



    private void downloadImage_(String urlStr) {
        progressDialog = ProgressDialog.show(this, "", "Downloading Image from " + urlStr);
        final String url = urlStr;

        new Thread() {
            public void run() {
                InputStream in = null;

                Message msg = Message.obtain();
                msg.what = 1;

                try { in = openHttpConnection(url);
                    bitmap = BitmapFactory.decodeStream( in );
                    Bundle b = new Bundle();
                    b.putParcelable("bitmap", bitmap);
                    msg.setData(b); in .close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                messageHandler.sendMessage(msg);
            }
        }.start();
    }

    private InputStream openHttpConnection(String urlStr) {
        InputStream in = null;
        int resCode = -1;

        try {
            URL url = new URL(urlStr);
            URLConnection urlConn = url.openConnection();

            if (!(urlConn instanceof HttpURLConnection)) {
                throw new IOException("URL is not an Http URL");
            }
            HttpURLConnection httpConn = (HttpURLConnection) urlConn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            resCode = httpConn.getResponseCode();

            if (resCode == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return in;
    }

    private Handler messageHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ImageView img = (ImageView) findViewById(R.id.imageView1);
            img.setImageBitmap((Bitmap)(msg.getData().getParcelable("bitmap")));
            progressDialog.dismiss();
        }
    };
}

1 个答案:

答案 0 :(得分:1)

您不能在Android应用程序的主线程上使用Internet连接,请参阅here。它可能最容易使用AsyncTask但也有很多other个选项。可以找到更多信息here

相关问题