我需要在用戶退出應用程序後停止我的應用程序正在做的所有操作(如振動),我該怎麼做?我的應用在手機振動一段時間,用戶選擇,但如果用戶啓動,並退出應用程序..手機繼續振動的時間選擇..我該如何對待這個錯誤?當用戶離開應用程序時無法完成執行完成
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();
}
});
}
}
使用OnPause()和Onstop()後退出應用程序,找到一個Bug,振動結束......但是當我退出並阻止手機時,使用振動器解鎖手機,和電話「記住」我上次選擇振動......並開始!如何完全結束振動器(和緩衝器?)? – Rcgoncalves 2013-04-24 02:09:45