Android:如何使用AlarmManager每天调用一个函数

时间:2014-09-29 15:14:05

标签: java android function alarmmanager

我有一个跟踪应用程序,可以保存时间戳和坐标。 现在我希望每天23:55 o时将其保存到txt文件中。 是否可以在同一个Activity中使用AlarmManager打开我的书写功能? 我还没找到具体如何在同一个Activity中使用AlarmManager调用函数的东西。 你能给我一个具体的例子来说明这个吗?

我有以下代码:

...
public void onRegister() {
    locationClient.connect();

    // Set the time to 11:55:00 pm:
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 23);
    cal.set(Calendar.MINUTE, 55);
    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, LocationLogic.class);
    PendingIntent pi = PendingIntent.getService(this, 1, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
}
...

但是如何执行保存功能?

2 个答案:

答案 0 :(得分:0)

将您的文件编写代码移至Service;我建议使用IntentService,因为onHandleIntent内的所有内容都将在后台线程上运行,服务将在完成后自行停止。

public class LocationLogic extends IntentService {
    private static final String TAG = "MyService";

    /* Services must have a no-arg constructor */
    public LocationLogic() {
        super(TAG);
    }

    @Override
    public void onHangleIntent(Intent intent) {
        /* your code here */
    }
}

然后每天使用AlarmManager启动服务。

答案 1 :(得分:0)

您需要创建一个扩展BroadcastReceiver的类,该类将在服务运行时调用。

您可以在此处找到更多信息:http://www.learn-android-easily.com/2013/05/android-alarm-manager_31.html