【问题标题】:Get IP address of Android device using API使用 API 获取 Android 设备的 IP 地址
【发布时间】:2016-12-07 03:32:26
【问题描述】:

我正在尝试使用 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.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick 执行 android:onClick 的方法

我在 swift 中使用过这种方法,效果很好。我已经查看了所有其他方法,但这似乎很容易。

来自 Android Studio 的错误部分: --------- 崩溃开始 E/AndroidRuntime: 致命异常: main 进程:com.example.ramesh.getipaddress,PID:2381 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.ramesh.getipaddress/com.example.ramesh.getipaddress.MainActivity}:android.os.NetworkOnMainThreadException 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 在 android.app.ActivityThread.access$800(ActivityThread.java:151) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:135) 在 android.app.ActivityThread.main(ActivityThread.java:5254) 在 java.lang.reflect.Method.invoke(本机方法) 在 java.lang.reflect.Method.invoke(Method.java:372) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 引起:android.os.NetworkOnMainThreadException 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147) 在 java.net.InetAddress.lookupHostByName(InetAddress.java:418) 在 java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)

任何帮助将不胜感激。

谢谢

拉梅什

【问题讨论】:

  • 问题似乎与此 API 无关,但似乎与您的 onClickListener 有关。请提供您收到错误的完整代码和行号。
  • 根据要求添加了其余代码和错误部分。感谢您的帮助。

标签: android gradle module compilation


【解决方案1】:

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

您的代码将如下所示:

更新:对于第二个错误:这样做:

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

    } 

//创建一个异步任务类:

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;
     }

}

【讨论】:

  • 致命异常:主进程:com.example.ramesh.getmyip1,PID:2561 java.lang.IllegalStateException:在 android 的父或祖先上下文中找不到方法 onClick (MainActivity)(View) :onClick 属性定义在视图类 android.support.v7.widget.AppCompatButton 上,id 为 'button1'
  • 我面临同样的问题。如果我只是使用 onClick 并放置一个打印语句,那么每次都可以正常工作。只有网络的东西,它会给出错误
  • 它对我来说很好用。出现第一个错误是因为您在主线程中调用 geipify() 方法。通过上述更改,第一个错误应该得到解决。这个新错误来自 layout.xml 文件中的方法名称。我已经更新了我的答案
  • 感谢您的帮助。我也应该可以直接从 onCreate() 调用它?即不使用用户单击按钮?
  • 是的。绝对地。无需单击按钮,只需调用 new networkingTask().execute();来自 onCreate
猜你喜欢
  • 2013-06-29
  • 2019-02-09
  • 1970-01-01
  • 2019-08-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多