Autoclick in Android - android

I'm developing an Android application in which I have different buttons.
In particular there is one that, in addition to the user whenever pressed, I want "autoclick" every X seconds.

You can use ScheduledExecutorService to create timer and autoclicker like that.
private void yourFunction(){
//whatever you want
}
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourFunction();
}
});
ScheduledExecutorService scheduleTaskExecutor= Executors.newScheduledThreadPool(1);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
yourFunction();
}
}, 0, YourSeconds, TimeUnit.SECONDS);
and you should close ScheduledExecutorService in your activity's onDestroy method like that.
public void onDestroy() {
super.onDestroy();
if (scheduleTaskExecutor != null)
scheduleTaskExecutor.shutdownNow();
}

Related

application stops running and exit when press the button in android studio

cancelBtn = (Button) findViewById(R.id.btnCncl);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
countDownTimer.cancel();
//txtViewOff.setText("");
txtViewOn.setText("Countdown Timer Canceled");
//Timer to set visible text view
Timer t = new Timer(false);
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
txtViewOn.setText("");
}
});
}
}, 3000);
}
});
when i click on the button related to this code the app get crashes..i made this to cancel the timer
I have no clear idea about this without a crash log. But according to this code most probably it may be a null pointer exception. try below thing by adding a null check before call countdowntimer
if(countDownTimer != null){
countDownTimer.cancel();
}

CountDownTimer is not cancelled

I define the countdowntimer here.
Then, new countdowntimer is defined for this variable in an onclick method:
public void showQuestion(int questionNumber){
questionTimer = new CountDownTimer(10500,1000) {
#Override
public void onTick(long millisUntilFinished) {
remainingTime.setText(Long.toString(millisUntilFinished/1000));
}
#Override
public void onFinish() {
remainingTime.setText("0");
showCorrectAnswer();
}
}.start();
}
Then i cancel this timer on another button' onclick method;
public void selectOption(View view) {
questionTimer.cancel();
}
In this time, it is succesfully cancelled. Then i am doing the same again. showQuestion method is working in the same way.
public void showQuestion(int questionNumber){
questionTimer = new CountDownTimer(10500,1000) {
#Override
public void onTick(long millisUntilFinished) {
remainingTime.setText(Long.toString(millisUntilFinished/1000));
}
#Override
public void onFinish() {
remainingTime.setText("0");
showCorrectAnswer();
}
}.start();
}
It is started succesfully. When i want to cancel this timer on another button onclick method, it is not working. Not any error. I hope it could be clear. Thank you so much.
The issue with your code is the timer can be started multiple times (sometimes not intentional) before the first timer is finished or cancelled. In that case, when you try to cancel it, you can only cancel the first timer. To solve this issue, you only have to check whether the timer is running, if it is running, wait for it to finish or cancel.
Define a global parameter:
Boolean timerRunning = false;
public void showQuestion(int questionNumber){
if (timerRunning) return;
timerRunning = true;
questionTimer = new CountDownTimer(10500,1000) {
#Override
public void onTick(long millisUntilFinished) {
remainingTime.setText(Long.toString(millisUntilFinished/1000));
}
#Override
public void onFinish() {
remainingTime.setText("0");
showCorrectAnswer();
timerRunning = false;
}
}.start();
}
Your selection option method can be changed to below: check if the timer is null before cancelling it.
public void selectOption(View view) {
if (questionTimer != null) questionTimer.cancel();
timerRunning = false;
}
public void selectOption(View view) {
questionTimer.cancel();
questionTimer = null;
}

Schedule Executor's Schedule Method is Executing Only Once

I am trying to implement a sample schedule where I want the toast to be displayed every 10 seconds.But the schedule method is running only once.Is there any solution.
Here is my code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScheduledExecutorService scheduledExecutorService= Executors.newScheduledThreadPool(1);
scheduledExecutorService.schedule(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Hello Schedule", Toast.LENGTH_LONG).show();
}
});
}
},
10, TimeUnit.SECONDS);
}
}
Read the documentation on the difference between ScheduledExecutorService#schedule() and ScheduledExecutorService#scheduleAt*
You should be looking for scheduleAtFixedRate method.
scheduleAtFixedRate :
Creates and executes a periodic action that becomes enabled first
after the given initial delay, and subsequently with the given period;
that is, executions will commence after initialDelay, then
initialDelay + period, then initialDelay + 2 * period, and so on.
Documentaion
Example
ScheduledExecutorService scheduledExecutorService;
scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Hello Schedule",Toast.LENGTH_LONG).show();
}},2,10,TimeUnit.SECONDS);

Hide and make visible button every 5 second interval

Can it possible to make a button on screen which automatically visible and gone every 5sec interval?
By using this
b.setVisibility(View.VISIBLE);
we can visible and
b.setVisibility(View.GONE);
we can hide it.But I can't manage to make it by usin the time interval.
Any idea?please share.
There are a few different ways, one is a Handler and Runnable:
public class Example extends Activity {
private Handler mHandler = new Handler();
private Runnable alternate = new Runnable() {
public void run() {
// Alternate visible and not
mHandler.postDelayed(alternate, 5000);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler.postDelayed(alternate, 5000);
}
}
Use this
new CountDownTimer(9000000, 5000) {
public void onTick(long millisUntilFinished) {
if(b.getVisibility() == View.GONE)
b.setVisibility(View.VISIBLE);
else
b.setVisibility(View.GONE);
}
public void onFinish() {
//Restart timer if you want.
}
}.start();

how to include timer in my program?

i need to include timer in my application.i just gone through the example given in the sites.and tried to implement that in my program.but the thing is i dont know how to work with timer.in my program i want to start the timer on a button click.timer has to show in the screen.but the screen is a canvas(when we click on button it loads a canvas) with moving objects.when two objects collide timer has to stop and has to show the value in a message box.given below is my main activity code.
public class MyActivity extends Activity {
private static final String TAG = MyActivity.class.getSimpleName();
public static Timer myTimer;
private Button startbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
startbtn=(Button)findViewById(R.id.startbtn);
startbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// making it full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// set our MainGamePanel as the View
setContentView(new MainGamePanel(getApplicationContext()));
Log.d(TAG, "View added");
}
});
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
#Override
protected void onDestroy() {
Log.d(TAG, "Destroying...");
super.onDestroy();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopping...");
super.onStop();
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
}
};
}
i know how to check collision.i need only timer part like starting timer,showing on the screen and stopping it from another class.can anybody help me...plz....
Use this the code will be repeated after one second and timer will run for 30sec
new CountdownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
finish();
}
}.start();

Categories

Resources