Question

Je suis en train d'avoir mon IntentService montrer un message Toast, mais lors de l'envoi du message onHandleIntent, les spectacles du pain grillé, mais est bloqué et l'écran et jamais à feuilles. Je devine que sa parce que la méthode onHandleIntent ne se produit pas sur le fil de service principal, mais comment puis-je déplacer?

Quelqu'un at-il a cette question et a résolu le problème?

Était-ce utile?

La solution

dans onCreate() initialize un Handler puis poster à partir de votre fil.

private class DisplayToast implements Runnable{
  String mText;

  public DisplayToast(String text){
    mText = text;
  }

  public void run(){
     Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
  }
}
protected void onHandleIntent(Intent intent){
    ...
  mHandler.post(new DisplayToast("did something")); 
}

Autres conseils

Voici le code complet IntentService classe démontrant Toasts qui m'a aidé:

package mypackage;

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

public class MyService extends IntentService {
    public MyService() { super("MyService"); }

    public void showToast(String message) {
        final String msg = message;
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        showToast("MyService is handling intent.");
    }
}

Utilisez la poignée pour poster un Runnable dont le contenu de votre opération

protected void onHandleIntent(Intent intent){
    Handler handler=new Handler(Looper.getMainLooper());
    handler.post(new Runnable(){
    public void run(){ 
        //your operation...
        Toast.makeText(getApplicationContext(), "hello world", Toast.LENGTH_SHORT).show();
    }  
}); 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top