1

我正在制作一个应用程序,它使用 AlarmManager 和广播接收器在每天上午 8:20 生成通知。

我面临的一个问题是,每次我在上午 8:20 之后打开应用程序时,都会生成通知。

我想这是因为我在onCreate()方法中调用了接收器。
有没有办法确保接收者只注册一次?

这是我的代码:

public class MainActivity extends AppCompatActivity
{

    AlarmManager alarmManager;
    private PendingIntent alarmIntent;

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


        alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 00);
        calendar.set(Calendar.MINUTE,30);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
 }

public class AlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context,"Alarm Raised",Toast.LENGTH_SHORT).show();
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        PendingIntent pendingIntent=PendingIntent.getActivity(context,0,intent1,0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setSmallIcon(R.drawable.ic_account_circle_black_18dp);
        builder.setContentTitle("Tracker");
        builder.setContentText("Turn on Gps");
        builder.setPriority(Notification.PRIORITY_MAX);
        builder.setDefaults(Notification.DEFAULT_SOUND);
        builder.setLights(0x0000FF,3000,2000);
        builder.setContentIntent(pendingIntent);
        notificationManager.notify(56, builder.build());
    }
}
4

1 回答 1

0

的第二个参数setInexactRepeating表示AlarmManager 应该什么时候开始它的任务。因此,如果您在过去给它一段时间,它会立即触发一次。您必须检查 calendar.getTimeInMillis() 是否在现在之前,如果是,则添加一天。

所以你应该简单地改变你的这部分代码

alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);

对此:

long timeToStart = calendar.getTimeInMillis();
if(System.currentTimeMillis() < timeToStart){
    timeToStart += 24 * 60 * 60 * 1000; // one day
}
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeToStart, AlarmManager.INTERVAL_DAY, alarmIntent);
于 2015-12-11T23:19:52.900 回答