计算 URL 的大小时出现问题

Trouble in calculating the size of URL

我想知道 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");
    }
}

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

后台线程 上进行网络调用

所有 url 任务在后台完成,因此为此使用异步任务 class ...... 下面的代码......看起来像这样

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

            }
        }

并调用它的 onCreate() 方法看起来像这样……

 new SignInAsyncTask().execute();