Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 当我尝试使用Inet显示我的ip时,为什么我的应用程序会崩溃?_Android - Fatal编程技术网

Android 当我尝试使用Inet显示我的ip时,为什么我的应用程序会崩溃?

Android 当我尝试使用Inet显示我的ip时,为什么我的应用程序会崩溃?,android,Android,我正在尝试使用Inet显示我的ip地址,但当我这样做时,应用程序崩溃。。 我是否需要添加任何权限以避免发生这种情况?下面是我的代码 try { Inet4Address ip= (Inet4Address) Inet4Address.getLocalHost(); String s=ip.toString(); TextView text= (TextView)findViewById(R.id.txt);

我正在尝试使用Inet显示我的ip地址,但当我这样做时,应用程序崩溃。。 我是否需要添加任何权限以避免发生这种情况?下面是我的代码

try {
            Inet4Address ip= (Inet4Address) Inet4Address.getLocalHost();
            String s=ip.toString();
            TextView text= (TextView)findViewById(R.id.txt);
            text.setText(s);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

android没有授予u在主线程中直接运行任何网络相关工作的权限,因此您会遇到以下异常:

android.os.NetworkOnMainThreadException 
按如下方式运行代码:

Thread thread = new Thread(){
        public void run(){
            try {
                Inet4Address ip= (Inet4Address) Inet4Address.getLocalHost();
                String s=ip.toString();

             TextView text= (TextView)findViewById(R.id.txt);
              text.setText(s);
                Log.e("my ip=> ",s+" <<");
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
    };

    thread.start();
Thread-Thread=新线程(){
公开募捐{
试一试{
Inet4Address ip=(Inet4Address)Inet4Address.getLocalHost();
字符串s=ip.toString();
TextView text=(TextView)findViewById(R.id.txt);
text.setText(s);

Log.e(“my ip=>”,s+”出于调试目的,捕获一般异常并查看logcatAttach崩溃日志。下面是日志的链接:它显示android.os.networkMainThreadException如何处理?如何处理?:-将其从主线程中删除,使用AsyncTask或其他线程