簡體   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