BreakHead
BreakHead

Reputation: 10672

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

Upvotes: 4

Views: 14723

Answers (2)

Dan S
Dan S

Reputation: 9189

You're making an assumption here that the device act likes an emulator. It's definitely running your application independently, not emulating or simulating. You'll have to adjust the IP address to your computer's IP address that the phone can see from its network, cellular or Wifi.

Upvotes: 1

user534042
user534042

Reputation:

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.

Upvotes: 5

Related Questions