Petrica
Petrica

Reputation: 37

Android run method each 5 minues

I have a Timer that makes some stuffs each 5 minutes. The question is where should i add this method? because if i add it in the "on create" method my Timer method executes only when my app is started. And i want to execute it each 5 minutes . Thanks in advice !

 private void timer() {
    final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleWithFixedDelay(new Runnable() {
      @Override
      public void run() {
        // fetching file
        tcpClient.execute();
      }
    }, 0, 60, TimeUnit.SECONDS);
  }

EDIT : it looks like i need an AlarmManager as Peter Birdsall and Aleksander Lidtke said EDIT2: Now i have an AlarmManager set up , but still I can't run that method each 5 minutes , I'm new to Android , where should I call these things ? If i add it on the on create method it executes only 1 time, but i want it to execute forever , each 5 minutes.

THIS Saved ME https://github.com/rakeshcusat/Code4Reference/blob/master/AndroidProjects/AlarmManagerExample/AndroidManifest.xml

Upvotes: 3

Views: 10047

Answers (4)

superuser
superuser

Reputation: 731

Put this in the oncreate, it will not only execute once, I am absolutely positive.

            Timer myTimer = new Timer();
            myTimer.schedule(new TimerTask() {
               @Override
               public void run() {
                   tcpClient.execute();
               }
            }, 0, 300000);

Upvotes: 7

Developer
Developer

Reputation: 6350

Use this code it will help u call a function modify it according to u r requirement

private final long refreshDelay = 5 * 1000;
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //setContentView(R.layout.main);

            sendHttpRequestThread = new SendHttpRequestThread("","");
            sendHttpRequestThread.start();

        }

     class SendHttpRequestThread extends Thread {

            boolean sendHttpRequest;
            String userId;
            String pass;

            public SendHttpRequestThread(String str1, String str2) {
                this.userId = str1;
                this.pass = str2;
                sendHttpRequest = true;
            }

            public void stopSendingHttpRequest() {
                sendHttpRequest = false;
            }

            protected void onStop() {
                sendHttpRequestThread.stopSendingHttpRequest();
                super.stop();
            }

            @Override
            public void run() {
                while (sendHttpRequest) {
                    //Call U r function from here 

                    SystemClock.sleep(refreshDelay);
                }
            }
        }

Upvotes: -1

Peter Birdsall
Peter Birdsall

Reputation: 3425

I'm working on a similar type app. I use a broadcastreceiver and a service that schedules it using the alarmmanager, that way you don't have much overhead, like running a timer, which has to stay active.

Here's my main activity. I initiate the sequences with buttons.

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

}



Button.OnClickListener btnOnClickListener = new Button.OnClickListener() {

    @Override
    public void onClick(View v) {

        if (v == btn_splash) {
                initiateAlarm(true);
                Toast.makeText(MainActivity.this, " alarm scheduled", Toast.LENGTH_LONG).show();
            }
            } else if (v == btn_cancel)
                {

                initiateAlarm(false);

                Toast.makeText(MainActivity.this, " alarm stopped", Toast.LENGTH_LONG).show();
                }
    }

};



} 

public void initiateAlarm(Boolean bactive) {
      alarmUp = false;
        alarmUp = (PendingIntent.getBroadcast(getBaseContext(), 0, 
               new Intent(this, YourService.class), 
               PendingIntent.FLAG_NO_CREATE) != null);
                if (alarmUp)
                    {
                    Log.d("myTag", "Alarm is already active");
                    Toast.makeText(this, " before scheduling Alarm is already active", Toast.LENGTH_LONG).show();
                    } else {

                        YourReceiver.scheduleAlarms(this, prefDuration, bactive);
                        Toast.makeText(this, "alarms were just scheduled", Toast.LENGTH_LONG).show();
                    }


         alarmUp = false;
         alarmUp = (PendingIntent.getBroadcast(getBaseContext(), 0, 
                new Intent(this, YourService.class), 
                PendingIntent.FLAG_NO_CREATE) != null);
                if (alarmUp)
                    {
                    Log.d("myTag", "Alarm is already active");
                    Toast.makeText(this, " after scheduling Alarm is already active", Toast.LENGTH_LONG).show();
                    }
}

}

Here's the YourReceiver that schedules the service in the alarmmanager.

public class YourReciever extends BroadcastReceiver {

private static final String TAG = "YourReciever";



@Override
public void onReceive(Context ctxt, Intent i) {
  context = ctxt;

  scheduleAlarms(ctxt, (long) 3600001, true);  // 1 hour - not used

 }

 static void scheduleAlarms(Context ctxt, Long duration, Boolean bactive) {

  Log.e(TAG, " ... scheduleAlarms ");
  SharedPreferences preferences; 

  preferences = PreferenceManager.getDefaultSharedPreferences(ctxt); 
  prefDuration = preferences.getLong(PREF_DURATION, 3600000);  // 1 hour
  Log.e(TAG, " ... onReceive ... duration: " + duration);  

AlarmManager mgr=
    (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(ctxt, YourService.class);
PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);


mgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
                 SystemClock.elapsedRealtime() + duration, duration, pi);
if (bactive == false) {
    mgr.cancel(pi);
}


 }

}

and finally here's the service class

public class YourService extends IntentService {




public YourService() {
    super("YourService");
    Log.e(TAG, " ... YourService");

}


@Override
protected void onHandleIntent(Intent intent) {


//
//  The action you want to perform.
//


}

}

Something like this needs be in the manifest.

 <service
        android:name="com.yourpackagename.YourService"
        android:exported="true"/>

Hope this helps.

Have a good day.

Upvotes: 1

NathanTempelman
NathanTempelman

Reputation: 1387

Try using the Action time tick broadcast. Here's an article that'll show you how. Very simple.

http://androidbridge.blogspot.ca/2011/08/how-to-use-actiontimetick-broadcast.html

That ticks every minute, so then in the reciever you just want to include something like

tick++
if(tick>=5)
{
    //Do what you want to do here

    tick=0;
}
else
{
    return;
}

Upvotes: 0

Related Questions