2016-12-07 88 views
0

我想從ipify使用API​​獲取android設備的IP地址。我嘗試使用https://www.ipify.org/中建議的API。很簡單。使用API​​獲取Android設備的IP地址

<?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

我已經使用這個方法迅速和它的作品的onClick:爲Android無法執行方法正好。我已經看過所有其他方法,但看起來很簡單。從Android Studio中

錯誤部分: 碰撞 E/AndroidRuntime的---------開頭:致命異常:主 工藝: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) 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) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 產生的原因:在android.os.StrictMode $ AndroidBlockGuardPolicy android.os.NetworkOnMainThreadException .onNetwork(StrictMode.java:1147) at java.net.InetAddress.lookupHostByName(InetAddr ess.java:418) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)

任何幫助將不勝感激。

感謝

拉梅什

+0

問題似乎沒有與此API,但它似乎與您的onClickListener。請提供您收到錯誤的完整代碼和行號。 – nitinsh99

+0

根據請求添加了代碼的其餘部分和錯誤部分。感謝你的幫助。 –

回答

0

爲完整的代碼去看起來像你的acitivty崩潰,因爲你正試圖執行主線程上的網絡電話。您必須在後臺線程中進行聯網。你可以和應該使用異步任務來實現這一目標:

你的代碼看起來就像這樣:

更新:對於第二個錯誤:這樣做:

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

} 
+0

致命例外:main 進程:com.example.ramesh.getmyip1,PID:2561 java.lang.IllegalStateException:無法在父級或祖先上查找方法onClick(MainActivity)(View)上下文中定義的android:onClick屬性查看ID爲'button1'的android.support.v7.widget.AppCompatButton –

+0

我正面臨同樣的問題。如果我只是使用onClick並放置打印語句,那麼它每次都能正常工作。在網絡上的東西,它給錯誤 –

+0

這對我來說工作得很好。第一個錯誤是因爲你在主線程中調用geipify()方法而來的。有了上述更改,首先應該解決錯誤。這個新的錯誤來自您的layout.xml文件中的方法名稱。我已經更新了我的回答 – nitinsh99