Android 当我尝试使用Inet显示我的ip时,为什么我的应用程序会崩溃?
我正在尝试使用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);
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或其他线程