run code periodically android

Solutions on MaxInterview for run code periodically android by the best coders in the world

showing results for - "run code periodically android"
Malak
25 Apr 2016
1/* USING HANDLER METHOD */
2Handler myHandler = new Handler();
3int delay = 1000; // 1000 milliseconds == 1 second
4
5myHandler.postDelayed(new Runnable() {
6    public void run() {
7        System.out.println("myHandler: here!"); // Do your work here
8        handler.postDelayed(this, delay);
9    }
10}, delay);
11
12/* USING ALARM MANAGER METHOD */
13// Some time when you want to run
14Date when = new Date(System.currentTimeMillis());
15
16try {
17    Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched
18
19    // Note: this could be getActivity if you want to launch an activity
20    PendingIntent pendingIntent = PendingIntent.getBroadcast(
21        context,
22        0, // id (optional)
23        someIntent, // intent to launch
24        PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
25    );
26
27    AlarmManager alarms = (AlarmManager) context.getSystemService(
28        Context.ALARM_SERVICE
29    );
30
31    alarms.setRepeating(
32        AlarmManager.RTC_WAKEUP,
33        when.getTime(),
34        AlarmManager.INTERVAL_FIFTEEN_MINUTES,
35        pendingIntent
36    );
37} catch(Exception e) {
38    e.printStackTrace();
39}
40
41/* THEN RECEIVE YOUR INTENT */
42public class MyReceiver extends BroadcastReceiver {
43    @Override
44    public void onReceive(Context context, Intent intent)
45    {
46        System.out.println("MyReceiver: here!") // Do your work here
47    }
48}
49
50/* THEN REGISTER YOUR RECEIVER */
51MyReceiver receiver = new MyReceiver();
52context.registerReceiver(receiver, intentFilter);