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
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();
}
621 GDB gets version error when attempting to debug with the Presense SDK (IDE)
585 PHP ssh2_scp_send fails to send files as intended
926 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
631 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.