使用API​​

时间:2016-12-07 03:32:26

标签: android gradle module compilation

我正在尝试使用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:致命异常:主要                   处理: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)                       at java.lang.reflect.Method.invoke(Native Method)                       在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)                       at java.net.InetAddress.lookupHostByName(InetAddress.java:418)                       at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)

任何帮助将不胜感激。

由于

拉​​梅什

1 个答案:

答案 0 :(得分:0)

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

您的代码将如下所示:

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

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

}