I'm making a timer inside an app (in Studio), and when the timer reaches 0, it vibrates. I would like to make it so that the phone still vibrates when the screen is locked. Any suggestions?
Here's my main activity:
EditText timerWrite;
ImageButton power;
ImageButton check;
TextView minsLeft;
CountDownTimer countDownTimer = null;
Vibrator vibe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
timerWrite = (EditText) findViewById(R.id.timerWrite);
power = (ImageButton) findViewById(R.id.power);
check = (ImageButton) findViewById(R.id.check);
minsLeft = (TextView) findViewById(R.id.minsLeft);
power.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
vibe.cancel();
if(countDownTimer != null)
countDownTimer.cancel();
minsLeft.setText("stopped");
}
});
check.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
vibe.cancel();
if (countDownTimer != null)
countDownTimer.cancel();
String text = timerWrite.getText().toString();
if (!text.equalsIgnoreCase("")) {
int mins = Integer.valueOf(text);
countDownTimer = new CountDownTimer(mins * 60000, 1000) {
@Override
public void onTick(long milliseconds) {
long minutes = milliseconds / 60000;
long seconds = (milliseconds / 1000) % 60;
minsLeft.setText(getString(R.string.minutes) + (int) (minutes) + " seconds:" + (int) (seconds));
}
@Override
public void onFinish() {
minsLeft.setText("Are You OK?");
long[] pattern = {0, 1000, 2000, 100};
vibe.vibrate(pattern, 1);
}
}.start();
}
}
});
}
Thanks!
That would be beyond the Activity life cycle as it would go to onPause()
and onStop()
hence your code/app wont work, what you are looking for is a Service that will run without these limitation.
https://developer.android.com/guide/components/services.html
Cheers.