Damian Piwowarski
Damian Piwowarski

Reputation: 814

Android and checking for new data per hour

Im creating a news-like app and I want to know is is possible to start app (ex : 1 time per 1h) to check if new data is available. You know what im talking about, I think. App should start from nowhere, check and finish().

Is this possible? I know that widgets can do it but normal activity or something like this?

Please, help. Damian.

Upvotes: 0

Views: 713

Answers (1)

Gopal Nair
Gopal Nair

Reputation: 840

Yes, It is possible to use an "Alarm Service" in android, and use it to perform some work, at specific intervals.

Here is the link to Alarm Service documentation: http://developer.android.com/reference/android/app/AlarmManager.html

Here is a sample code which uses Alarm Service

    /**
     * Method to start background service for server refresh and other tasks.
    */
    public void startMyService()
    {
        //Start Service service to handle data refresh
        Intent serviceIntent = new Intent(this, MyCommunicationService.class);

        //Schedule additional service calls using alarm manager.
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getService(this, 0, serviceIntent, 0);

        //Retrieve time interval from settings (a good practice to let users set the interval).
        MyPreferenceManager prefManager = new MyPreferenceManager(this);        
        alarmManager.cancel(pi);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), prefManager.getDataRefreshTime()*1000  , pi);

    }

Note that we are multiplying with 1000, because the parameter for setRepeating() method is in milliseconds.

Upvotes: 1

Related Questions