How to Repeat a Method Every 10 Minutes After a Button Press and End It on Another Button Press

How do I repeat a method every 10 minutes after a button press and end it on another button press

Create a BroadcastReceiver

public class AlarmReceiver extends BroadcastReceiver
{

@Override
public void onReceive(Context context, Intent intent)
{
//get and send location information
}
}

and add the same to your AndroidManifest so that the Receiver is registered

<receiver
android:name="com.coderplus.AlarmReceiver"
android:exported="false">
</receiver>

Now you can set a repeating alarm from your Activity which will invoke the receiver every 10 minutes:

AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),600000,
pendingIntent);

and to cancel the alarm, call cancel() on the AlarmManager using an equivalent PendingIntent

AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.cancel(pendingIntent);

or if you don't want to use AlarmManager / BroadcastReceiver, then something like this will help you out. Before you go for it, check - difference between timer and alarmmanager

private class MyTimerTask extends TimerTask {
@Override
public void run() {
//get and send location information
}
}

initialize the Timer and Timer task:

Timer myTimer = new Timer();
MyTimerTask myTimerTask= new MyTimerTask();

Stopping or starting the Timer

//to Stop
myTimer.cancel();
//to start
myTimer.scheduleAtFixedRate(myTimerTask, 0, 600000); //(timertask,delay,period)

Refer
http://developer.android.com/reference/java/util/TimerTask.html

http://developer.android.com/reference/java/util/Timer.html

Using a thread to use a method every interval

private class MyTimerTask extends TimerTask {
@Override
public void run() {

mDialogHandler.sendEmptyMessage(DIALOG_OK);

}

}

private Handler mDialogHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case DIALOG_OK:
// We are now back in the UI thread
//textView.setText("changed");
readWebpage(text);
}

};
};

You're trying to start a Thread from inside a thread which is illegal. I also added some code for your UI Thread woes.

turning function to occur every 5 seconds instead of every button click

You can use javascript to make the loop with 5 seconds.

<script>

window.setInterval(function(){
goFwd(e)
}, 5000);

</script>

when you want to stop the loop you can use: clearInterval()

Updated

You can make the button auto click after 5 seconds. Then your function will call automatically after every 5 seconds.

<script>

var btn = document.getElementById('your_button_id');
setInterval(function(){
btn.click();
}, 5000); // this will make it click again every 5 seconds

</script>

how record values in the android SQLite DB every 5 minutes?

You can use RxJava to accomplish this task in a couple of seconds.

and use these dependencies:

 implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.0.1'

Disposable disposable = Observable.interval(5, TimeUnit.MINUTES)
.doOnNext(n -> YOUR_FUNCTION_NAME()).subscribe();

REPLACE YOUR_FUNCTION_NAME with your function name

When you need to stop this just use the below code:

 if (!disposable.isDisposed())
disposable.dispose();

Android How to execute a method every x hours or minutes

As you mentioned we will schedule an alarm to execute a method at a particular time in future.

We will have two classes

  1. MainAcitvity: in this class, we will schedule the alarm to be
    triggered at particular time .
  2. AlarmReciever: when the alarm
    triggers at scheduled time , this class will receive the alarm, and
    execute a method.

AlarmReciever class extends BroadcastReceiver and overrides onRecieve() method. inside onReceive() you can start an activity or service depending on your need like you can start an activity to vibrate phone or to ring the phone

Permission Required
we need permission to use the AlarmManger in our application, so do not forget to declare the permission in manifest file

AndroidManifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.src"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!-- permission required to use Alarm Manager -->
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

<application
android:icon="@drawable/ic_launcher"
android:label="Demo App" >
<activity
android:name=".MainActivity"
android:label="Demo App" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<!-- Register the Alarm Receiver -->
<receiver android:name=".AlarmReciever"/>

</application>
</manifest>

main.xml

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_vertical"
xmlns:android="http://schemas.android.com/apk/res/android">

<TextView
android:id="@+id/textView1"
android:gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Alarm Manager Example"
android:textAppearance="?android:attr/textAppearanceLarge" />

<Button
android:id="@+id/button1"
android:layout_marginTop="25dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Schedule The Alarm"
android:onClick="scheduleAlarm"/>

</LinearLayout>

MainActivity.java

public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

public void scheduleAlarm(View V)
{
// time at which alarm will be scheduled here alarm is scheduled at 1 day from current time,
// we fetch the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000 milliseconds in a day
Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;

// create an Intent and set the class which will execute when Alarm triggers, here we have
// given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers and
//we call the method inside onRecieve() method of Alarmreciever class
Intent intentAlarm = new Intent(this, AlarmReciever.class);

// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();

}
}

AlarmReciever.java

public class AlarmReciever extends BroadcastReceiver

{
@Override
public void onReceive(Context context, Intent intent)
{
//call the method here

}

}

What is the best way to repeatedly execute a function every x seconds?

If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print("Doing stuff...")
# do your stuff
sc.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

If you're already using an event loop library like asyncio, trio, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.

script - click button every x seconds

you can use jQuery to trigger a click event'

setInterval(function(){
$( "input" ).trigger("click");
},random(3000,4000));

function random(min,max){
return min + (max - min) * Math.random()
}


Related Topics



Leave a reply



Submit