Robospice service running until it finish it job after application finished - android

I have an application that access to a server. When I quit the application, I have to disconnect from the server first, then close the application.
I would like to know if it's possible (and how) to make a Robospice service (background task) that disconnect from the server even if the application is closed (and the Robospice service is still running to finish the deconnection, and then auto kill itself after).
The problem is that the deconnection is too long (sometimes more than 5 secondes) and I would like to avoid blocking the phone during the deconnection, and allow the user to use it's phone.
Another question : is the Robospice librairy will be maintained and improved in the future (if necessary) ?

Yes, RoboSpice works just as well when attached to a Service Context as it works with an Activity one.
But you should probably try executing disconnect in the com.octo.android.robospice.SpiceService#onDestroy method of your implementation. This service is stopped whenever it has no meaningful work to do, so I guess it is the most appropriate solution for your use case.

I've solved my problem (that may be wasn't really a problem !) by ending my application with finish()
In my MainActivity, I use a Robospice service :
private final class LogoutListener implements PendingRequestListener<String> {
#Override
public void onRequestFailure(SpiceException spiceException) {
Log.e(TAG, spiceException.getMessage());
}
#Override
public void onRequestSuccess(String result) {
// nothing special
}
#Override
public void onRequestNotFound() {
Log.w(TAG, "Not found");
}
}
private void Alarm_Logout(boolean exit) {
Logout request = new Logout(url);
spiceManager.execute(request, new LogoutListener());
this.finish();
}
And the Lougout class :
public class Logout extends OkHttpSpiceRequest<String> {
private String url_logout;
public Logout(String url) {
super(String.class);
this.url_logout = url;
}
#Override
public String loadDataFromNetwork() throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url_logout)
.build();
Response response = client.newCall(request).execute();
return "ok";
}
}
Before I closed the app with System.exit(0) in onRequestSuccess, so I had to wait the Logout complete. Now the app close (with finish()), but the Logout continue in background, and then, when done, the service finish...

Related

LibGDX http request not working

I want to send a String message to database when user presses a specific button in the LibGDX game I am designing for android. How do I go about doing that? Following is the code I tried. But it does not work.
Net.HttpRequest httpRequest = new Net.HttpRequest();
httpRequest.setMethod("POST");
httpRequest.setUrl("URL is here");
httpRequest.setContent("INSERT INTO `game_table` (`Button`) VALUES ('Button 1 Pressed')");
Net.HttpResponseListener httpResponseListener = new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
Gdx.app.log("Log httpResponse", httpResponse.getResultAsString());
}
#Override
public void failed(Throwable t) {
}
#Override
public void cancelled() {
}
};
Gdx.net.sendHttpRequest(httpRequest,httpResponseListener);
Log does not provide anything in android monitor. I also tried using AsyncTask and without AsyncTask to implement this code. But neither works.
Am I missing something? If so could you give me small code snippet that will work?
You don't need to use an AsyncTask, libGDX' HTTPRequest is async out of the box.
You did not log anything if the request fails or is cancelled so probably that's the case.

Android App using Volley get race condition

I'm developing an Android Mobile Application and one of the most important functionality of the app itself is being able to talk with a third-party API Service.
The third party service, offering these API, wants a "beacon" to be included into every API request i made.
The "beacon" is a "long integer" and it must be unique and incremental for every request.
The problem is:
I'm firing a couple of these request and i do not know which of these requests will complete first so i'm running into a race condition: where the second request ends quickly before the first request invalidating the first request!
When a button is clicked the following action will be executed:
public void fireRequests(View view)
{
long first_beacon = System.nanoTime();
fireFirstRequest(view, first_beacon);
long second_beacon = System.nanoTime();
fireSecondRequest(view, second_beacon);
}
I'm using Volley in a proper way, setting up callback etc.. example here:
fireFirstRequest method:
public void fireFirstRequest(View view, long beacon)
{
final ThirdPartyLib api_lib = new ThirdPartyLib(getActivity());
api_lib.doOperationA(beacon, new ThirdPartyLib.MyOwnCallback()
{
#Override
public void update(JSONObject jsonObject)
{
try
{
JSONObject result = jsonObject.getJSONObject("response");
/* my code */
Log.d("doOperationA", result)
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
}
fireSecondRequest method:
public void fireSecondRequest(View view, long beacon)
{
final ThirdPartyLib api_lib = new ThirdPartyLib(getActivity());
api_lib.doOperationB(beacon, new ThirdPartyLib.MyOwnCallback()
{
#Override
public void update(JSONObject jsonObject)
{
try
{
JSONObject result = jsonObject.getJSONObject("response");
/* my code */
Log.d("doOperationB", result)
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
}
Here is the execution log:
03-12 14:26:56.252 18769-18769/it.example.app D/Volley: queued doOperationA
03-12 14:26:58.124 18769-18769/it.example.app D/Volley: queued doOperationB
03-12 14:26:59.433 18769-18769/it.example.app D/App: doOperationB: {
"error": false,
"payload": {
"foo": "bar"
}
}
03-12 14:27:04.181 18769-18769/it.example.app D/App: doOperationA: {
"error": true,
"errorMessage": "invalid beacon"
"payload": {}
}
The question is: what's the best way to keep track of beacon before firing an API request or to maintain a "execution order" separation even if we are talking of ASync request?
My rough solution is to call the fireSecondRequest() inside the callback of the fireFirstRequest() when i'm completely sure that first request is done.
I know, this is the best way to kill the awesome world of async requests.
modified action:
public void fireRequests(View view)
{
long first_beacon = System.nanoTime();
fireFirstRequest(view, first_beacon);
}
fireFirstRequest modified method with final View parameter:
public void fireFirstRequest(final View view, long beacon)
{
final ThirdPartyLib api_lib = new ThirdPartyLib(getActivity());
api_lib.doOperationA(beacon, new ThirdPartyLib.MyOwnCallback()
{
#Override
public void update(JSONObject jsonObject)
{
try
{
JSONObject result = jsonObject.getJSONObject("response");
/* my code */
Log.d("doOperationA", result)
/* fire second request */
// EDIT
fireSecondRequest(view, System.nanoTime());
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
}
You didn't add the part of your code which initiates the Volley RequestQueue, but I'm assuming you're creating the default way using:
RequestQueue requestQueue = Volley.newRequestQueue(context, stack);
When you do this, you get a request queue which allows for 4 concurrent requests by default. You can see this by looking at the constructor this method uses to create a request queue:
private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;
...
public RequestQueue(Cache cache, Network network) {
this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE);
}
You can overcome this issue if instead of using the default method for creating a RequestQueue, you create your own RequestQueue with a thread pool size of 1. This way, there can be no 2 concurrent requests, and requests will be sent in the order they are dispatched.
The downside with this, of course, is that this can dramatically slow down your app. If all requests must wait until the previous request is finished, this creates a serious bottleneck in your app.
Perhaps consider using more than 1 request queue, and only use this special request queue for requests that rely on this special constraint.
Hope this helps.

Pause current stack, log in and resume for Volley when there is a 401

I'm currently trying to build a Volley app that handles resuming after a 401-status code.
Say that my application is in a middle of a sync and I receive a 401 error, I'll need to get a new token, I want to pause the current Volley RequestQueue, add the failed requests back onto the RequestQueue, popup a login display box, and send a login request. Once the server sends me the needed details I will then resume the main RequestQueue.
The current solution I'm working on is that my onErrorResponse will pause the stack then shows a login box. Send a login request on another RequestQueue, wait for a reply and then resume the main RequestQueue. But I'm unsure how to restart any failed requests that were failed by the 401 error.
Is this the right direction, if so how can I add my requests back onto the queue from the onErrorResponse method?
You can set your login request a higher priority than your sync, and set more relaxed retry policies to your sync requests. For example:
private class LoginRequest extends com.android.volley.toolbox.JsonObjectRequest {
...
#Override
public Priority getPriority() {
return Priority.HIGH;
}
}
and, for your sync requests:
public class SyncRequest extends com.android.volley.toolbox.JsonObjectRequest {
...
#Override
public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
return super.setRetryPolicy(new SyncRetryPolicy());
}
}
public class SyncRetryPolicy extends com.android.volley.DefaultRetryPolicy {
private static final int INITIAL_TIMEOUT_MS = 5500;
private static final int MAX_NUM_RETRIES = 10;
private static final float BACKOFF_MULTIPLIER = 2f;
public SyncRetryPolicy() {
super(INITIAL_TIMEOUT_MS, MAX_NUM_RETRIES, BACKOFF_MULTIPLIER);
}
}
Of course it only makes sense if the user is fast enough to login. In a case where the user just leaves the device in the login screen, you'll need a more robust system.
How important is the sync? Is viable for you to save it in disk for syncing later? And if the user multitask to another app while in the login screen, and the OS decides to deallocate your app from memory?

Android : DbxAccountManager.hasLinkedAccount() always return false on Remote Service

On my Activity :
public class MainActivity extends Activity {
private mDbxAccountManager mDbxAccountManager = null;
...
#Override
public void onCreate(Bundle savedInstanceState) {
...
mDbxAccountManager = DbxAccountManager.getInstance(getApplicationContext(), getString(R.string.dbx_app_key), getString(R.string.dbx_app_secret));
...
}
...
public void buttonOnClick(View view) {
if(mDbxAccountManager.hasLinkedAccount()) {
//Do something
}
else {
mDbxAccountManager.startLink(this, 0);
}
...
}
}
And on my Remote Service :
public class CloudService extends Service {
private mDbxAccountManager mDbxAccountManager = null;
#Override
public void onCreate() {
...
mDbxAccountManager = DbxAccountManager.getInstance(getApplicationContext(), getString(R.string.dbx_app_key), getString(R.string.dbx_app_secret));
if(!mDbxAccountManager.hasLinkedAccount()) {
return;
stopSelf();
}
...
}
}
The result is, after I link my app with dropbox using installed dropbox client, the hasLinkedAccount() on my Activity return true, meanwhile the same code on my Remote Service always return false.
I also check the logcat and it showed that my app already linked with dropbox.
My suspect is that the dropbox API create some SharedPreferences when it successfully link with my app, but my Remote Service can't access that or get a cached version of that SharedPreferences... I don't know...
Please help...
Thank you
Edited :
If I reinstall the app, then the result is as expected and hasLinkedAccount() return true, but if I uninstall and install again which cause clearing the user-data, then I link my app again with Dropbox, then the same strange behaviour appear again.
What I'm doing wrong? I'm turning my head almost 24-hours....
Solved!!!
After trying and trying...
I get conclusion that the Service that runs before the app linked with dropbox will always get DbxAccountManager.hasLinkedAccount() return false.
I try to kill the process by calling Process.killProcess(myservicePid) after I link my app with Dropbox and start the service again and it work.
So... I solved it by not starting the service before the app was linked with dropbox and start the service only if it already linked, because stopSelf() on the service doesn't kill the process.
I think this issue have something to do with the Context getApplicationContext() which is passed to DbxAccountManager.getInstance(), and I don't know why looks like the Context is not updated when the dropbox was link with the app.
Thank you.

Android - security through inheritence

I want to extend a common security check to nearly every view of my application. To do this, I have made this class
public class ProtectedActivity extends ActivityBase {
boolean isAuthenticated = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread validationThread = new Thread()
{
#Override
public void run()
{
try
{
isAuthenticated = UserService.validateToken();
}
catch (FTNIServiceException e)
{
//eat it
}
finally
{
if (!isAuthenticated)
{
startActivity(new Intent(ProtectedActivity.this, SignInActivity.class));
finish();
}
}
}
};
validationThread.start();
}
}
The logic is simple. Validate the user against my restful api to make sure they are signed in. If they aren't, show them to the signin page.
This works great, because to add the security check, all I need to do is inherit from my ProtectedActivity.
public class MainMenuActivity extends ProtectedActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
The problem is, however, that I periodically receive View not attached to window manager errors. I understand why this is happening. I am starting a new intent in the parent class, and the child lives on. to attempt to alter it's view even though a new intent has started. What is a better way to handle this so that if a user is not authenticated (such as their session expires serverside), it won't error when sending the user to the sign in screen?
Don't you Thread. Use AsyncTask instead which should handle your references to windows correctly.
On a different note, I would change this to a different implementation. Why don't use the Preferences storage on the phone to store some kind token. If the token is not valid then request a new token and all the stuff you are doing currently. This way is better because you don't want to request a REST call every time.
I imagine something like this (pseudo code)
Check if credentials exist in Preference
if(valid) then do nothing
else use AsyncTask and pop up a loader screen "Waiting..."

Categories

Resources