炒空心菜 2016-11-25 09:31 采纳率: 66.7%
浏览 1465
已采纳

Android activity 中 打开Url 网络地址报错

public void dialog(View view)
{
String msg="";
Toast toast=Toast.makeText(this, "", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);

    LinearLayout layout=(LinearLayout)toast.getView();
    layout.setMinimumHeight(50);
    ImageView image=new ImageView(getApplicationContext());
    image.setImageResource(R.drawable.ic_launcher);
    image.setMaxHeight(50);
    image.setMaxWidth(50);
    layout.addView(image, 0);
    TextView txt=new TextView(getApplicationContext());

    try
    {

        String url_1="http://192.168.43.1:8080/android/legendary.db",url_2="http://localhost:8080/android/legendary.db";
        URI uri=new URI(url_2);
        URL url=uri.toURL(); 
        url.openConnection();
        InputStream in=url.openStream();
        toast.setText("---->");
        txt.setText("\n-----****");
        txt.setTextColor(Color.parseColor("#ffaaff"));
    }
    catch (Exception e)
    {
        msg = e.toString();
        e.printStackTrace();
        txt.setText(e.toString() + "\n-----****");
        txt.setTextColor(Color.RED);
        txt.setTextSize(16);

    }
    layout.addView(txt, 1);
    toast.show();

latelog2(msg);
setlog2();
notice("错误---->", msg);

}

/*错误信息
android.os.NetworkOnMainThreadException
*/

展开全部

  • 写回答

5条回答 默认 最新

  • 全栈极简 博客专家认证 2016-11-25 16:27
    关注

    错误信息是不能在主线程中进行网络相关的操作。应该用thread+handler或者asynctask处理。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)
编辑
预览

报告相同问题?