Android app does not access the local server

Hey guys!

I’m developing an ionic app and generated an apk for android platform, I managed to install it on my phone, but I can’t access the server (I’m using xampp), so I can’t login to use the app.

Provider

 @Injectable()
export class AccessProviders {
  server: string = 'http://192.168.43.253/phpp/';
  constructor(
      public http: HttpClient,
      public allertCrtl: AlertController,

  ) {}

  postDate(body, file) {
      let headers = new HttpHeaders({
          'Content-Type': 'application/json; charset=UTF-8'
                });
      let options = {
          headers: headers
      }
      return this.http.post(this.server + 'SubmeterDados.php/'+ file, JSON.stringify(body),
          options).timeout(59000).map(res => res);
  }

AndroidManifest

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="io.ionic.starter" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:networkSecurityConfig="@xml/network_security_config" android:supportsRtl="true" android:usesCleartextTraffic="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

In the browser, through ionic serves (both local and external) everything works, but the apk doesn’t.

From what I gather, you are running the API endpoint http://192.168.43.253/phpp/ on your computer via XAMPP and you installed the APK on your physical Android device. For this to work, you need to make sure both devices are on the same network and port 80 is open on your computer so your Android device can access it.

Thank you very much, I’ll try this tip, then I’ll give you the answer

If this is the only environment you’re ever going to run this app in, and it’s effectively just a personal project, then you can stop reading here.

If you’re ever going to distribute it, then I think it doesn’t make any sense to continue until you’ve got a production-ready setup going, because you will just end up dealing with a bunch of irrelevant concerns. That means:

  • use hostnames, never numeric IP addresses
  • no plaintext HTTP, get SSL certificates and use https:// endpoints

Incidentally, there’s needless cruft in your HTTP code. Don’t manually make headers, don’t manually stringify things, don’t map something to itself. HttpClient is smart enough to do all that for you, and having that junk in there obscures the important part of the code.

The entirety of postDate can and should be one line:

return this.http.post(`${this.server}/SubmeterDados.php/${file}`, body)

Local server is not accessable when running on Real Device,
You have to make another steps to make it work
I already stumbled on this issue, heres the solution on my end

That is good advice @rapropos. I would say though that this specific scenario of needing to use a physical Android device connecting to a local dev server for the backend isn’t necessarily that unique and not a waste of time to get working. I myself have a similar set up due to not being able to run the Android emulator and a virtual machine running my API backend at the same time (due to CPU constraints of not being able to run two different virtual environment tech stacks at the same time).

For my setup, I am using ionic cap run android -l --external for live reload on my physical Android device that connects to the VM on my laptop running my backend.

A couple notes of my setup:

  • I use environment build variables to set my base API URL in my Ionic Vue app
  • I do use the IP address of my laptop as the host for the API URL as I don’t have the ability to create a DNS record for a FQDN on my network
  • I don’t use HTTPS locally for the API (definitely do in production!) but have my laptop’s IP in Android’s network config to allow clear text traffic
  • In my laptop’s firewall, I have allowed the port for live reload and the port for my API only from my Android’s phone IP

Overall, it is a semi-complicated setup but from what I know, it is the only free solution other than not running a VM so the Android emulator can run :slight_smile: but I don’t want the database and everything else the API relies on running on my physical machine.

FWIW, what I do in a development situation like this is to completely mock out the backend:

interface Mothership {
  allWidgets(): Observable<Widget[]>;
  widgetById(id: string): Observable<Widget | null>;
  ...
}

class MothershipService implements Mothership { ... real thing }
class MothershipMock implements Mothership { ... dummy data }

class AppModule {
  providers: [
    // comment me out for production
    { provide: MothershipService, useClass: MothershipMock },
    // comment me out for development
    MothershipService
  ]
}

But once I get far enough along, I spin up a tiny VM in the cloud, put nginx on it, set DNS up, get an SSL cert from LetsEncrypt, and then use that in conjunction with local DNS served by a router. I use OpenWRT to do the local DNS, but I’m sure there are plenty of other options.

1 Like

Thanks for the attention of everyone who gave me great advice here, I’m satisfied. Actually it’s not a personal application, I’ll distribute it as soon as I’m done, now I just wanted to test it and I ended up getting it with Ionic serve - - external.
I will correct it according to the recommendations given here. Thanks

1 Like