How do I avoid interrupting communication by switching apps when I communicate from Android to the cloud?

Asked 2 years ago, Updated 2 years ago, 46 views

Hello,

I asked a question that I wanted to know how to safely send the relatively important data that I entered in Activity.
When you send data from Android, it takes 3-5 seconds to process, and there is a server that can return the results with JSON.

What happens to http communication when a user switches apps while sending data to this server?
If I generate Thread in Activity, will Thread kill when the app is hidden?

Apparently, there are AsyncTask and AsyncTaskLoader on Android, so please let me know how to safely send data to the server.

android

2022-09-30 15:05

1 Answers

AsyncTask performs background processing and delivers results to UI threads:
* The doInBackground method sends data to the server on a different thread
* The results are sent to the onPostExecute method

Thus, if your Activity is killed, it will not enter onPostExecute:

private class DownloadFilesTask extensions AsyncTask<URL, Integer, Integer>{

    protected Integer doInBackground (URL...urls) {
        // This is running on a different background thread
        return 0;
    }

    protected void onPostExecute (Integer result) {
        // US>This is running on the UI thread
    }
}

It is recommended that you use the background Service for long-term tasks (Background Service link, for example:

_IntentService:

public class HttpService extensionsIntentService{

    public HttpService(){
        super("HttpService");
    }

    @ Override
    protected void onHandleIntent(Intent int){

        // Retrieve data from Intent
        String parameters = intent.getStringExtra("fruit");

        // Now I'm going to send you the data.
    }
}

_AndroidManifest:

<application
    android: icon="@drawable/icon"
    android: label="@string/app_name">

    .....

    <service
        android:name = ".HttpService"
        android:exported="false"/>

<application/>

_Activity:

...
    IntentmServiceIntent=newIntent(this,HttpService.class);
    mServiceIntent.putExtra("fruit", "apple";
    // Starts the IntentService
    startService(mServiceIntent);
    ...

Notes:

Do not assume that Service or AsyncTask is not interrupted.If Android requires memory, a thread (AsyncTask or Service) may be killed.

To address this, save the state of the app.Restarting the app checks the previous state:

SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(this);

boolean shouldSend=preferences.getBoolean("send", false);
if(shouldSend){
    SharedPreferences.Editor editor=preferences.edit();
    editor.putBoolean("send", true);
    editor.apply();
    // Now I'm going to send you the data.

    .....

    editor.putBoolean("send", false);
    editor.apply();
}


2022-09-30 15:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.