Android IntentService调用不会自行停止的toast

Hov*_*nky 0 android

我搞砸了android网站上关于服务的例子.这项服务是为了祝酒.我使用按钮的onClick方法启动服务.它有效,但吐司永远不会结束!我认为IntentService在进程完成后专门停止.

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;

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


     @Override
     protected void onHandleIntent(Intent intent) {
         Toast.makeText(this, "Starting service", Toast.LENGTH_SHORT).show();
     }

 }
Run Code Online (Sandbox Code Playgroud)

Sam*_*Sam 5

我曾经那样做过,这让我觉得很傻......

您可以保存对Toast的引用并取消它onDestroy().或者只是不在如此短暂的服务中与UI交互.

Toast toast;

@Override
protected void onHandleIntent(Intent intent) {
    toast = Toast.makeText(this, "Starting service", Toast.LENGTH_SHORT);
    toast.show();
}

@Override
public void onDestroy() {
    toast.cancel();
}
Run Code Online (Sandbox Code Playgroud)