繁体   English   中英

使用API​​获取Android设备的IP地址

[英]Get IP address of Android device using API

我试图使用ipify的API获取Android设备的IP地址。 我尝试使用https://www.ipify.org/中建议的API。 很简单。

<?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====");
     }

}

由于某种原因,它不会打开流。 我收到了错误

java.lang.IllegalStateException:无法执行android的方法:onClick at android.support.v7.app.AppCompatViewInflater $ DeclaredOnClickListener.onClick

我在swift中使用过这个方法,效果很好。 我看过所有其他方法,但这看起来很容易。

来自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)由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)

任何帮助将不胜感激。

谢谢

拉梅什

通过完整的代码看起来你的活动正在崩溃,因为你试图在主线程上执行网络调用。 您必须在后台线程中进行联网。 您可以而且应该使用异步任务来实现此目的:

你的代码看起来像这样:

更新:对于第二个错误:执行此操作:

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

    } 

//创建一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM