2

私は Android 開発を始めており、現在はサービスを学んでいます。
文字列を継続的にトーストする簡単なサービスを作成しました。
サービスの開始と停止には 2 つのボタンを使用しました。
開始ボタンをクリックすると、サービスが開始され、文字列が継続的にトーストされます。
しかし、停止ボタンをクリックしてサービスを停止しようとすると、停止しません。
ストリングを連続的にトーストし続けます。

public class MyService extends Service {

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

        doToast();

        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }


    public void doToast()
    {
        final Handler handler= new Handler();
        handler.postDelayed(new Runnable(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Toast.makeText(MyService.this, "hi", 0).show();
                handler.postDelayed(this, 3000);
            }

        }, 3000);

    }

}

これは、サービスを開始および停止するためのコードです

startservice.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        startService(new Intent(getBaseContext(), MyService.class));
    }
});

stopservice.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        stopService(new Intent(getBaseContext(), MyService.class));
    }
});
4

1 に答える 1

4

As MD mentioned, even though you are stopping the service, you have to remove the callbacks since the runnable is still in the message queue, waiting to post itself again. That is:

public class AwesomeService extends Service {
// other stuff
  private int DELAY = 2000;
  Handler mHandler = new Handler();
  Runnable toastRunnable;
  public void doToast() {
    mHandler.postDelayed(getToastRunnable(), DELAY);
  }
  private Runnable getToastRunnable() {
    Runnable r = new Runnable() { 
      @Override public void run() {
        // show toast
        // doToast()
      }
    };
    toastRunnable = r;
    return r;
  }
...
  // and to remove the callbacks,
  @Override public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(toastRunnable);
  }
}
于 2015-03-27T17:09:36.130 に答える