用户退出应用程序后,我需要停止我的应用程序正在执行的所有操作(例如振动),我该怎么做?我的应用程序会在用户选择的一定时间内振动手机,但如果用户启动并退出应用程序..手机会继续振动所选的时间..我该如何处理这个错误?
public class MainActivity extends Activity {
EditText tempo;
Button bt;
Thread t;
int estado = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempo = (EditText) findViewById(R.id.tempo);
//long delay = Long.parseLong(tempo.getText().toString());
bt = (Button) findViewById(R.id.btvibrar);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (!tempo.getText().toString().equals("")) {
if (estado == 1) {
Vibrar();
estado *= -1;
bt.setText("Parar !");
bt.setBackgroundColor(Color.RED);
//Handler handler = new Handler();
//handler.postDelayed(new Runnable() {
//@Override
//public void run() {
//estado*=-1;
//bt.setText("Vibrar !");
//bt.setBackgroundColor(Color.GREEN);
//}
// }, );
} else {
Parar();
estado *= -1;
bt.setText("Vibrar !");
bt.setBackgroundColor(Color.GREEN);
}
} else {
AlertDialog.Builder dialogo = new AlertDialog.Builder(MainActivity.this);
dialogo.setTitle("Erro !");
dialogo.setMessage("Escolha um tempo.");
dialogo.setNeutralButton("OK", null);
dialogo.show();
}
}
private void Vibrar() { // É necessario lançar excessao no ANDROIDMANIFEST.XML
Vibrator rr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long treal = Long.parseLong(tempo.getText().toString());
long milliseconds = treal * 1000;
rr.vibrate(milliseconds);
}
private void Parar() {
Vibrator rr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
rr.cancel();
}
});
}
}