3

我想在 7 天后重复发布数据。为此,我使用警报管理器 setRepeat 方法。当手机重新启动时,警报会被清除。我使用引导接收器并再次设置警报。

但是,如果手机在第 6 天重启并再次设置闹钟,则闹钟将在第 6+7 天响起,而不是在第 7 天响起。有什么办法解决吗??

对不起我的英语不好。请帮忙

4

2 回答 2

7

设置警报时,将触发时间保存在共享首选项中。并在启动接收器中再次设置警报,但在这种情况下,触发时间来自共享首选项。

于 2012-08-02T07:56:44.927 回答
1

在你的 AndroidManifest.xml

<receiver android:name="com.Company.PackageName.BootCompletedReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

在您的 com.Company.PackageName.BootCompletedReceiver 类中

public class BootCompletedReceiver extends BroadcastReceiver 
{
    private Context mContext;
    private G9SharedPreferences oSharedPreferences;
    private AlarmManager amSchedules;

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        this.mContext = context;
        oSharedPreferences = new G9SharedPreferences(this.mContext);
        try 
        {
            vUpdateAlarmManager();  
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
        finally
        {
            oSharedPreferences = null;
            this.mContext = null;
        }
    }

    @SuppressWarnings("deprecation")
    public void vUpdateAlarmManager()
    {
        vCancelAlaramManager();
        Date dCurrentDate = new Date(oSharedPreferences.GetLongPreferences(G9Constant.BACKUP_TIME, 0));     
        if(dCurrentDate.getTime() < new Date().getTime())
        {
            dCurrentDate.setDate(dCurrentDate.getDate() + 1);
        }
        vSetRepeatingAlarm(dCurrentDate);
    }

    public void vCancelAlaramManager()
    {
        Intent oIntent = new Intent(mContext, AlarmReceiver.class);
        PendingIntent oPendingIntent = PendingIntent.getBroadcast(mContext, 0, oIntent, 0);
        AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(oPendingIntent);
        oPendingIntent.cancel();
    }

    public void vSetRepeatingAlarm(Date dScheduleTime)
    {
        amSchedules = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(mContext, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        amSchedules.setRepeating(AlarmManager.RTC_WAKEUP, dScheduleTime.getTime(), AlarmManager.INTERVAL_DAY , pendingIntent);
    }
}
于 2012-08-02T08:32:54.187 回答