【问题标题】:java.net.URL in android.., application immediately closed, newbie [duplicate]android中的java.net.URL ..,应用程序立即关闭,新手[重复]
【发布时间】:2016-08-12 06:59:53
【问题描述】:

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

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

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

我的目标是访问 url。我的意思是获取 html 代码,然后解析它。首先尝试,获取图像 url 成功(未使用函数中的示例),但对于普通 url,我被卡住了。谢谢你的帮助..

我的完整代码:

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();
        }
    };
}

【问题讨论】:

  • 我们需要您的 logcat,而不是您的完整代码。
  • 我在哪里可以得到那个?我还在学习 java.. 我直接在我的手机上测试,如果我使用 avd 需要一段时间来完成加载..
  • 你不应该直接在手机上开发 - 只能最后。如果它在模拟器中运行良好,它将在设备上运行得更快。或者,您的应用程序可能会在您的超级泵设备上正常运行,而在低端设备上像蜗牛一样行走。无论如何,即使您在手机上运行该应用程序,仍然会生成 logcat。
  • 发生这种情况是因为您正在主线程上进行网络操作。如果不尝试使用 asyctasks,请使用一些 libaray
  • @Rotwang,好吧,我冒这个险.. 那么,当我在手机中运行我的应用程序时,logcat 在哪里?

标签: java android networkonmainthread


【解决方案1】:

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

【讨论】:

  • 所以跟测试不一样? cz 当我测试它时,它的工作原理。 Toast.makeText(MainActivity.this, "online", Toast.LENGTH_SHORT).show();在主显示屏中显示结果..
猜你喜欢
  • 2018-12-06
  • 2016-09-26
  • 2019-01-27
  • 2011-12-17
  • 1970-01-01
  • 2017-07-06
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多