I need to stop all that my app is doing (like vibrating) after the user quit the aplication, how can i do that ? My app vibrate the phone for certain amount of time that the user choose, but if the user start, and quit the app .. the cellphone continues to vibrate for the time chosen.. How can i treat this error ?
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();
}
});
}
}
First of all, you need to differentiate between quitting, and pausing the application(a pause happens if another application comes to the foreground). Secondly, you need to override the appropriate methods to handle what happens when the application is paused or destroyed.
For example, overriding
protected void onPause() {}
will allow you to define what should happen when the application is paused, hence, you can gracefully stop whatever your application is doing.
Similarly, you can implement onStop
and onDestroy
if needed. But in your case, I believe onStop
and onPause
will be sufficient :)
Also, try giving this page a look, it gives a detailed description of the activity lifecycle http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle