Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

java - http://10.0.2.2 works on the android emulator but not on android device used as a emulator

I connected my android device via USB to use it as a emulator, if I access the URL from eclipse emulator it works but the same if I access from device as emulator it gives connection time out error.

is there any settings do I need to change for this? or is there any possible solution for this?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is what I had to do in order to get the device to pick up a local service instance on my windows PC running on localhost.

  • Turn on WiFi on my device and connect to the wireless network.
  • Run ipconfig in the command prompt.
  • Use the IPv4 Address for my Ethernet Adapter Local Area Connection (since I'm connected via ethernet)
  • Change the base url in the android application to use that address

Then my android application was able to connect to the local service instance via that IP address rather than 10.0.2.2, which works when you're running the application on the emulator. If one was so inclined, you could extract those urls and check whether the application was running on the emulator or the device, and then set the ip address appropriately in code. Hope this helps.

Edit in regard to above url extraction - I created an ApplicationName.java file and declared this variable:

public static String ANDROID_DEVICE_ID = "";

Then set that variable in my initial activity:

ApplicationName.ANDROID_DEVICE_ID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

Then I copy pasted that device Id, and in my api class that makes the web service calls I have the following code:

private String getCategoriesUrl() {
    // TODO: Remove before production
    if (AgoraApplication.ANDROID_DEVICE_ID.equals("deviceIdString")) {
        _categoriesUrl = _deviceIp + _categoriesUrlSuffix;
    }
    else {
        _categoriesUrl = _emulatorIp + _categoriesUrlSuffix;
    }
    return _categoriesUrl;
}

So when I'm debugging on either device or emulator my application automatically uses the appropriate IP address for service calls.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...