APK only works with local server!?

I am fairly new to Capacitor. It took me a day to figure out what was going on when the built apk would not work if I stop my local server. Hope the following solution could help somebody who encounters the same situation.

<Develop Android app with Ionic + Capacitor in Windows>

[ Situation ]

I used this command to live reload and test the app
$ ionic cap run android -l --external

The following lines are added automatically into capacitor.config.json

  "server": {
    "url": "http://192.168.8.15:8100",
    "cleartext": true

After testing, I stopped the live server in cmd (Ctrl + C).
The capacitor.config.json was reverted back automatically.

I built the app-debug.apk in Android Studio > Build > Build Bundle(s) / APK(s) > Build APK(s)
The apk was then installed in an Android phone.
A blank screen was shown, saying that it could not connect to my local host.

Before running the cap live server, all the app-debug.apk builts were working fine on the phone.
After running live server, things were messed up.
So what was going on?

[ Explanation ]
When “server url” is set in capacitor.config.json, the built apk will only work if the live server is running.
We definitely want to remove this setting.

The cap live server only live reloads updates of pages / components / etc.
App level configs are not updated.
i.e. Android Studio will not know any update in capacitor.config.json after the live server has run.
That is why even the server url settings were removed, the built apk was still not working.

We have to “sync” the project in order to make things work.

[ Solutions ]

  1. Stop live server
  2. run $ ng build
  3. run $ npx cap sync android
  4. Build the apk again in Android Studio

Note the file size of the built apk. You will find that the file size of the “wrong” apk is about half of the “correct” one.
Please correct me if I am wrong.

1 Like

Spent a day on this.

Thanks for this!

Make server conditional in capacitor.config.ts

...
  server: process.env.ENV === 'development'
    ? {
        url: `http://192.168.8.15:8100`,
        cleartext: true,
      }
    : {},
...

Hi,

i have exactly the same problem.

I use IONIC 5 and the the URL ( “url”: “http://172.20.1.103:8100” ) is in the file capacitor.config.json
Is there a way to put a if-then-else into the json file to fix the problem.

Or even better, is there a offical solution for this problem.

Best regards
Dietmar

You can use a capacitor.config.ts file instead of a capacitor.config.json file if you need if/else statements.