2017-09-06 5 views
0

Je n'ai qu'une seule activité, lorsque l'utilisateur ferme l'application (à partir d'une liste claire des applications récentes) Je veux envoyer une requête à mon serveur API et changer le statut de l'utilisateur. donc je fais IntentService et l'appelle dans ma méthode onDestroy(), mais ça ne marche pas. comment le faire? Y a-t-il un autre moyen de faire cela (envoyer une requête au serveur avant que l'application ne tue compeletly)? mon code:Android Demande au serveur avant que l'application soit compeletly fermée

Activité:

@Override 
protected void onDestroy() { 
    Intent intent = new Intent(this, MakeOfflineIntentService.class); 
    intent.putExtra(Variables.INTENT_TOKEN, Token); 
    intent.setAction("ACTION_MAKE_OFFLINE"); 
    startService(intent); 
    super.onDestroy(); 
} 

et dans mon IntentService:

public class MakeOfflineIntentService extends IntentService { 

private static final String ACTION_MAKE_OFFLINE = "ACTION_MAKE_OFFLINE"; 

private static final String EXTRA_TOKEN = Variables.INTENT_TOKEN; 

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

public static void startActionFoo(Context context, String param1) { 
    Intent intent = new Intent(context, MakeOfflineIntentService.class); 
    intent.setAction(ACTION_MAKE_OFFLINE); 
    intent.putExtra(EXTRA_TOKEN, param1); 
    context.startService(intent); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    if (intent != null) { 
     final String action = intent.getAction(); 
     if (ACTION_MAKE_OFFLINE.equals(action)) { 
      final String param1 = intent.getStringExtra(EXTRA_TOKEN); 
      retrofitBaseInformationChange(param1,Variables.OFFLINE,1); 
     } 
    } 
} 

private void retrofitBaseInformationChange(final String Token, final int online, int vehicle){ 
    RetrofitCallServer retrofitCallServer = new RetrofitCallServer(WebServiceUrls.RETROFIT_INFORMATION_CHEETAH_MAN); 
    OnCallBackRetrofit onCallBackRetrofit = retrofitCallServer.getResponse(); 

    Call<OBRbaseInfromationChange> call = onCallBackRetrofit.askBaseInformationChange(Token,online,vehicle); 
    call.enqueue(new Callback<OBRbaseInfromationChange>() { 

     @Override 
     public void onResponse(Call<OBRbaseInfromationChange> call, Response<OBRbaseInfromationChange> response) { 
      /*response gotten maybe success or not*/ 
      if (response.isSuccessful()){ 
       OBRbaseInfromationChange obr = response.body(); 
       if(obr.code == 200){ 
        Log.i(Variables.APP_TAG,"BaseInformationChange successful"); 
       } 
       else{ 
        Log.i(Variables.APP_TAG,"BaseInformationChange error code: "+obr.code); 
       } 
      }// end if response successful 
      else { 
       Log.i(Variables.APP_TAG,"BaseInformationChange not Successful: "+response.code()); 
      } 
     } 

     @Override 
     public void onFailure(Call<OBRbaseInfromationChange> call, Throwable t) { 
      /*our request not sent or conversion problem*/ 
      Log.i(Variables.APP_TAG,"onFailure BaseInformationChange: "+t.getMessage()); 
     } 

    }); 
} 
// end retrofitBaseInformationChange() 

} 

et enfin ici est dans mon manifeste:

<service 
     android:name=".Services.MakeOfflineIntentService" 
     android:exported="false" 
     android:stopWithTask="false"/> 

Répondre

1

Avez-vous essayé de retourner START_STICKY dans le onStartCommand override? Après avoir envoyé votre demande, vous pouvez ensuite appeler le stopService pour vous arrêter. Pour autant que je sache, même les services collants peuvent être "recréés" lorsque vous tuez l'application. Alors peut-être, une intention n'est pas la meilleure façon d'utiliser ici.

je partirais avec SharedPreferences ici:

  • Le onCreate de votre application définit la clé "app_offline" à "false"

  • Les onDestroy ensembles cette touche à "true" et commence le service

  • Le service est START_STICKY et quand il trouve le "app_offline" comme vrai, envoie sa requête, met à jour "app_offline" à false (le réinitialise), puis exécute un auto-arrêt.

Quelque chose comme ça. Hope this helps, Cheers, Gris

+0

Je n'ai pas utilisé START_STICKY befor, permettez-moi de Google et faire essayer.merci –

+0

merci pour votre aide, je le résoudre ce jour-là, ça aide, maintenant je copie une partie de mon code ici pour une réponse plus complète –

1

merci pour la réponse Grisgram, je résous le problème et coller mon code ici pour réponse plus complète:

Je fais une variable nom SharedPreferences IS_APP_CLOSED. lorsque l'application ouverte onCreate:

saveL.saveInLocalStorage(Variables.IS_APP_CLOSED,false); 
    startServiceToMakeOffline(); 

méthode startServiceToMakeOffline() est:

private void startServiceToMakeOffline(){ 
    Intent intent= new Intent(this, MakeOfflineService.class); 
    startService(intent); 
} 

dans OnDestroy de cette activité:

@Override 
protected void onDestroy() { 
    saveL.saveInLocalStorage(Variables.IS_APP_CLOSED,true); 
    super.onDestroy(); 
} 

et voici ma classe de service:

public class MakeOfflineService extends Service { 

private boolean isAppClosed = false; 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    loadInfoFromLocalStorage(); 
    if(isAppClosed){ 
     askServer(); 
    } 

    return Service.START_STICKY; 

} 

@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

private void loadInfoFromLocalStorage() { 
    SharedPreferences prefs = getApplicationContext().getSharedPreferences(Variables.CHEETAH_NORMAL, 0); 
    isAppClosed  = prefs.getBoolean(Variables.IS_APP_CLOSED, false); 
    prefs = null; 
} 
// end loadInfoFromLocalStorage() 


private void askServer() { 
    //TODO: request server than when result gotten: 
    stopSelf(); 
} 
} 

et voici mon manifeste:

<service 
     android:name=".Services.MakeOfflineService" 
     android:stopWithTask="false"/>