question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to keep HTTP requests running in background? - Android

See original GitHub issue

First of all, awesome plugin. Now, I understand this is not exactly a plugin’s issue, but probably a very common scenario for it. I’m trying to watch and send the location via HTTP Post request to server as in the following code:

BackgroundGeolocation.addWatcher(
      {
        backgroundMessage:
          "Location is still tracked in background.",
        requestPermissions: true,
        stale: true,
        distanceFilter: 200,
      },
      async function (location) {
        if (location) {
          let formData = new FormData();
          formData.append("location", JSON.stringify(location));
          await ApiService.sendLocation(formData); // Does a simple HTTP post request using Axios.
        }
      }
    );

This is working fine in iOS indefinitely (as long as I grant the ‘Always’ location permission).

However for Android, this is not the case. I granted all battery/data usage permissions for my app in particular. After 5 minutes in background, the server will stop receiving locations. As soon as I enter the app again (it is not being killed btw, I can tell because it does not reload the splash screen) it will start sending all the buffered requests to server. So the location is being tracked correctly, but it seems like the HTTP requests get blocked and start to pile up.

Does this mean that I should actually do the HTTP request inside the native callback code? public void onLocationResult(LocationResult locationResult)

I would appreciate any insight, but as I said, I understand this is not precisely this plugin’s issue.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:26 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
JuanDeLeoncommented, Mar 19, 2021

@gbrits Yeah I switched from Axios to the Http plugin for this specific call.

So on this plugin’s callback I do:

async function (location) {
          if (location) {
            setNewMarkerPosition(location);
            sendLocation(location);
          }
        }

And this method will use Http community plugin, not axios.

const sendLocation = async (location) => {
      try {
        const access_token = await Storage.get({ key: "access_token" });

        await Http.request({
          method: "POST",
          url: process.env.VUE_APP_API_BASE_URL + "/sendLocation",
          headers: {
            Authorization: "Bearer " + access_token.value,
            Accept: "application/json",
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
          },
          data: {
            location: JSON.stringify(location),
          },
        });
      } catch (e) {
        console.log(e);
      }
    };
1reaction
JuanDeLeoncommented, Mar 19, 2021

If you need a quick try, you may overwrite this plugin’s native callback function and add something like the following.

HttpURLConnection con;
try {
    URL url = new URL("https://yourserver/sendLocation");

    Map<String,Object> locationJson = new LinkedHashMap<>();
    Map<String,Object> params = new LinkedHashMap<>();

    params.put("location", "{\"latitude\": " + location.getLatitude() + ", \"longitude\": " + location.getLongitude() + "}");

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("Authorization", "Bearer " + "tokenRawValueHere");
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.connect();

    con.getOutputStream().write(postDataBytes);

    Reader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

    for (int c; (c = in.read()) >= 0;)
        System.out.print((char)c);


} catch (ProtocolException e) {
    e.printStackTrace();
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Repeatedly send a HTTP request, even when app is in ...
The function gets called on startup; When I press the button with new LoadInfoClass().run(); , everything runs as predicted; But the the method ......
Read more >
Send work requests to the background service
The next step is to report the results of the work request back to the originating Activity or Fragment. The next lesson shows...
Read more >
Sending and Managing Network Requests - CodePath Cliffnotes
Wrap in AsyncTask and execute in background thread. This would translate to the following networking code to send a simple request (with try-catch...
Read more >
Background Processing in Android - Auth0
TL;DR: Android apps use the main thread to handle UI updates and operations (like user input). Running long-running operations on the main ...
Read more >
Android Create a HTTP Request without using any third party ...
You need to create an Async Task that will be running on background thread. P.S : The Android developers have restricted the HTTP...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found