I am creating an app that vibrate and beep every 30 sec and when I log out the vibrate and beep must be cancelled and when I log in the vibrate and beep should resume.
NOTE: it must vibrate and beep for every 30 sec until I log out
In my app I am using TimerTask for this implementation
this is the code for vibrate and beep using TimerTask
static TimerTask Task;
final static Handler handler = new Handler();
static Timer t = new Timer();
public static void vib() {
Task = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Vibrator vibrator = (Vibrator) ApplicationUtils.getContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(3000);
playSound();
Log.d("TIMER", "Timer set on");
}
});
}
};
t.schedule(Task, 0, 30000);
}
This is the code I’m using in logout section
public void stopvib() {
if (Task != null) {
// Log.d("TIMER", "timer canceled");
t.cancel();
Task.cancel();
}
}
Note: I also removed the Task.cancel(); but still I am getting same error
My vibrate working fine before logout and again login I am geting error
java.lang.IllegalStateException: Timer was cancelled
at java.util.Timer.scheduleImpl(Timer.java:562)
at java.util.Timer.schedule(Timer.java:481)
at com.vib(AlertListActivity.java:724)
can any one help me with this coding. Where did I go wrong?
i have recently run this code and is working fine. This can be achieved using broadcast Receiver.You have to implement separate CustomTimer task that extend TimerTask:
After this you have to implement BroadCast Receive in that class where you want to implement ” vib() ” method.:
Let say, in my case (just for example ) is MainActivity:
Now,you can start Or stop vibration by implementing these lines:
To start vibration:
To Stop:
Note:
onDestroy() of MainActivity (in your case,Where you implement Broadcast Receiver,unregister BroadcastReceiver.)