Hemantvc
Hemantvc

Reputation: 2119

Set timer for specific time, not interval

Is there any way to set a timer for a specific time instead of setting a timer for an interval (i.e. timer goes off after X (milli)seconds/minutes/hours)?

I need to make a phone call (programmatically) daily, exactly at 11:59.

Upvotes: 2

Views: 3220

Answers (4)

Isaac Urbina
Isaac Urbina

Reputation: 1313

You can do something like this in your code:

Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();

calSet.set(Calendar.HOUR_OF_DAY, YOUR_HOUR_HERE);
calSet.set(Calendar.MINUTE, YOUR_MINUTES_HERE);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);

if(calSet.compareTo(calNow) <= 0){
    //Today Set time passed, count to tomorrow
    calSet.add(Calendar.DATE, 1);
}
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);

I hope it helps!

Upvotes: 0

scottt
scottt

Reputation: 8371

Here's a sample app that shows how to combine the AlarmManager class with a service to do what you want. Just alter the time values and the doDailyAction() method in DoDaily.java to the time and action that you want to perform.

This approach resubmits a new alarm each day to avoid some of the problems associated with repeating alarms.

DoDaily.java

package com.example.daily;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class DoDaily extends Service {

    private final static String TAG = "DoDaily";

    @Override
    public void onCreate() {
        super.onCreate();

        Log.v(TAG, "Service started");                

        // Set an alarm for the next time this service should run:
        setAlarm();

        Log.v(TAG, "Service stopped");        
        stopSelf();
    }

    public void setAlarm() {
        // Set the time to 11:59:59 pm:
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 0);

        // Adjust calendar day if time of day has already occurred today:
        if (cal.getTimeInMillis() < System.currentTimeMillis())
            cal.add(Calendar.DAY_OF_MONTH, 1);

        Intent serviceIntent = new Intent(this, DoDaily.class);
        PendingIntent pi = PendingIntent.getService(this, 131313, serviceIntent,
                                                    PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
        Log.v(TAG, "Alarm set to " + cal.getTime().toString());

        doDailyAction();        
    }

    public void doDailyAction() {

        Log.v(TAG, "Doing daily action...");        
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

MainActivity.java

package com.example.daily;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

    private final static String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        Log.v(TAG, "Starting DoDaily service...");
        startService(new Intent(this, DoDaily.class));
    }
}

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.daily.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name="com.example.daily.DoDaily" >
        </service>
        </application>

</manifest>

Upvotes: 4

Lavekush
Lavekush

Reputation: 6166

Please use Timer , here is Tutorial.

or You can you AlarmManager:

Take a look at for AlarmManager: Trigger a function (code) at particular time

or You can also use CountDownTimer.

Working code:

CountDownTimer t = new CountDownTimer( Long.MAX_VALUE , 10000) {

        // This is called every interval. (Every 10 seconds in this example)
        public void onTick(long millisUntilFinished) {
            Log.d("test","Timer tick");
        }

        public void onFinish() {
            Log.d("test","Timer last tick");            
            start();
        }
     }.start();

Upvotes: 3

Lucifer
Lucifer

Reputation: 29632

You can use AlarmManager class for repeating actions.

Calendar calendar = Calendar.getInstance();
// 11:59 PM 
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent(context, MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);

Now Create a BroadcastReceiver with name MyClass

public class MyClass extends BroadcastReceiver 
{
        public void onReceive(Context context, Intent intent) 
        {
              // Write your function code here
        }
}

AlarmManager works even if your device is in sleep mode. AlarmManager helps you create scheduling repetative task in light weight mode, rather than creating long code to call a method again & again.

Upvotes: 8

Related Questions