计算URL大小时遇到​​麻烦

时间:2016-03-18 12:24:11

标签: android urlconnection

我想知道url的大小,以便下载文件但是它在运行时崩溃了。这是我的代码:

public class MainActivity extends AppCompatActivity {
    TextView t1;
    private int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t1=(TextView)findViewById(R.id.text1);
        try {


            URL url = new URL("https://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg");
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            i = conection.getContentLength();

        }
        catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        t1.setText(i + "MB");
    }
}

2 个答案:

答案 0 :(得分:0)

您的应用崩溃的原因是您在主线程上访问网络。您应该使用AsyncTask

后台主题上进行网络通话

答案 1 :(得分:0)

所有url任务都在后台完成,所以使用Async Task类为此........ 下面的代码......看起来像这样

$('div:contains("word2")').remove();

并将其称为onCreate()方法,看起来像是......

    class SignInAsyntask extends AsyncTask<String, String, String> {

            String result;

            @Override
            protected void onPreExecute() {

                super.onPreExecute();

            }

            @Override
            protected String doInBackground(String... strings) {

                 // doing all url works.................  
                  return result;
            }

            @Override
            protected void onPostExecute(String response) {

                super.onPostExecute(response);


                Log.e("Result", response);

            }
        }