[英]Get IP address of Android device using API
I am trying to get the IP address of the android device using an API from ipify. 我试图使用ipify的API获取Android设备的IP地址。 I tried using the API suggested in https://www.ipify.org/ .
我尝试使用https://www.ipify.org/中建议的API。 It is simple.
很简单。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ramesh.getipaddress">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
</application>
</manifest>
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public void onClick(View v) {
Log.i("Test", "End");
new networkingTask().execute();
//getContents("http://localhost:8080");
Log.i("Error", "Error1");
}
}
class networkingTask extends AsyncTask<String, String,String> {
protected String doInBackground(String... urls) {
//now call your ipify method which is doing the networking or calling a method that might be doing the networkign
//getContents("http://localhost:8080");
getipify();
return null;
}
public void getipify() {
try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("https://api.ipify.org").openStream(), "UTF-8").useDelimiter("\\A")) {
System.out.println("My current IP address is " + s);
} catch (java.io.IOException e) {
System.out.println("======");
System.out.println(e);
System.out.println("======");
}
Log.i("Test","====TEST====");
}
}
For some reason it wont open the stream. 由于某种原因,它不会打开流。 I get the error
我收到了错误
java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick java.lang.IllegalStateException:无法执行android的方法:onClick at android.support.v7.app.AppCompatViewInflater $ DeclaredOnClickListener.onClick
I have used this method in swift and it works just fine. 我在swift中使用过这个方法,效果很好。 I have looked at all other methods but this appears easy.
我看过所有其他方法,但这看起来很容易。
Error section from Android Studio: --------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.ramesh.getipaddress, PID: 2381 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ramesh.getipaddress/com.example.ramesh.getipaddress.MainActivity}: android.os.NetworkOnMainThreadException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.inter 来自Android Studio的错误部分:---------崩溃开始E / AndroidRuntime:FATAL EXCEPTION:main进程:com.example.ramesh.getipaddress,PID:2381 java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.ramesh.getipaddress / com.example.ramesh.getipaddress.MainActivity}:Android.app.ActivityThread.handleLaunchActivity(ActivityThread)上android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)的android.os.NetworkOnMainThreadException .java:2387)在Android.app.Handler.dispatchMessage(Handler.java)的android.app.ActivityThread.access $ 800(ActivityThread.java:151)android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1303) :102)在android.app.Looper.loop(Looper.java:135)的android.app.ActivityThread.main(ActivityThread.java:5254)在java的java.lang.reflect.Method.invoke(Native Method)。 com.android.inter上的com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:903)中的lang.reflect.Method.invoke(Method.java:372) nal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147) at java.net.InetAddress.lookupHostByName(InetAddress.java:418) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
nal.os.ZygoteInit.main(ZygoteInit.java:698)由java.InetAddress.lookupHostByName(InetAddress。)中的android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)中的android.os.NetworkOnMainThreadException引起。 java:418)at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
Any help will be greatly appreciated. 任何帮助将不胜感激。
Thanks 谢谢
Ramesh 拉梅什
Going through your full code looks like your acitivty is crashing because you are attempting to perform a network call on the main thread. 通过完整的代码看起来你的活动正在崩溃,因为你试图在主线程上执行网络调用。 You must do the networking in a background thread.
您必须在后台线程中进行联网。 You can and should use async task to achieve this:
您可以而且应该使用异步任务来实现此目的:
You code will look like this: 你的代码看起来像这样:
Update: For the second error: do this: 更新:对于第二个错误:执行此操作:
// just make sure to replace button with the id of your button
Button b = (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new networkingTask().execute();
}
});
public void onClick(View v) {
Log.i("Test", "End");
Log.i("Error", "Error1");
new networkingTask().execute();
}
//create a asynctask class: //创建一个asynctask类:
private class networkingTask extends AsyncTask<String, String,String> {
protected String doInBackground(String... urls) {
//now call your ipify method which is doing the networking or calling a method that might be doing the networkign
//getContents("http://localhost:8080");
getipify();
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.