2

所以我有一个BroadcastReceiver看起来像这样的:

public class UpdateReceiver extends BroadcastReceiver {

    public UpdateReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, 10);
        System.out.println("Broadcast received");       

        PendingIntent operation = PendingIntent.getService(context, 0,new Intent("REFRESH_THAT"), PendingIntent.FLAG_UPDATE_CURRENT);       
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), cal.getTimeInMillis(), operation);
    }
}

这就是我所说的BroadcastReceiver

 Intent in = new Intent ("REFRESH_BROADCAST");       
 sendBroadcast(in);

这是我在 AndroidManifest文件中的意图过滤器

<service android:name = ".services.RefreshService">     
    <intent-filter>
        <action android:name="REFRESH_THAT"/>
    </intent-filter>
</service>

<receiver android:name=".services.UpdateReceiver">        
    <intent-filter>
        <action android:name="REFRESH_BROADCAST"/>        
    </intent-filter>    
</receiver>

BroadcastReceiver收到了没有任何问题的广播,但AlarmManager似乎什么也没做。如果我称operation.send()它可以正常工作,那么我认为AlarmManager.

4

2 回答 2

3

好吧,最后我找到了解决方案,这是我的错。

我设置int type的 toAlarmManager.ELAPSED_REALTIMElong triggerAtMillistoSystem.currentTimeMillis()属性alarmManager.setInexactRepeating(.....)是错误的,它只能与AlarmManager.RTC / RTC_WAKEUP.

所以功能代码是这样的:

PendingIntent operation = PendingIntent.getService(context, 0,new Intent("REFRESH_THAT"), 0);       
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() , 30000, operation);

我真的应该更仔细地阅读 API 文档。如果您将鼠标悬停AlarmManager.ELAPSED_REALTIME,它会告诉您必须使用哪种时间触发器。希望我这个愚蠢的错误将来会对某人有所帮助。

于 2012-11-20T16:33:40.770 回答
0

根据setInexactRepeating文档,第三个参数是:

intervalMillis:警报的后续重复之间的间隔(以毫秒为单位)

然后你应该把10000ms (这是 10 秒)而不是cal.getTimeInMillis()

alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, cal.currentTimeMillis(), 10000, operation);

这意味着,您的警报将在意图触发 10 秒后响起,然后每 10 秒重复一次。当然,由于您使用的是这种方法,所以这是不准确的时机。

于 2012-11-20T13:32:11.020 回答