设置特定时间的计时器,而不是间隔

时间:2014-04-04 08:03:00

标签: android time

有没有办法在特定时间内设置定时器而不是为间隔设置定时器(即定时器在X(毫秒)/分钟/小时后关闭)?

我需要每天拨打电话(编程方式),完全是在11:59。

4 个答案:

答案 0 :(得分:7)

您可以使用 AlarmManager 类重复操作。

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);

现在创建一个名为MyClass

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

即使您的设备处于睡眠模式,AlarmManager也能正常工作。 AlarmManager可帮助您在轻量级模式下创建调度重复任务,而不是创建长代码来再次调用方法。试。

答案 1 :(得分:3)

这是一个示例应用程序,展示了如何将AlarmManager类与服务结合起来,以实现您想要的效果。只需将DoDaily.java中的时间值和doDailyAction()方法更改为您要执行的时间和操作。

此方法每天重新提交一个新警报,以避免与重复警报相关的一些问题。

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>

答案 2 :(得分:2)

请使用Timer,此处为Tutorial

或者你可以AlarmManager

查看 AlarmManager Trigger a function (code) at particular time

或您也可以使用CountDownTimer

工作代码:

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();

答案 3 :(得分:0)

您可以在代码中执行以下操作:

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);

我希望它有所帮助!