为什么多次调用BroadcastReceiver?

时间:2019-05-20 06:15:11

标签: java android broadcastreceiver alarmmanager

我每次打开应用程序时都会调用我的BroadcastReceiver的OnReceive(),尽管该警报仅在03.00 AM触发一次。

我记录了上次调用onReceive()的时间,所以我很确定onReceive()有点坏。而且似乎onReceive()代码仅在我真正启动应用程序后才执行,而不仅仅是在应用程序关闭时执行(并且应该执行实际代码)

MonthManager.java

public class MonthManager extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("BISASAM","triggered");
        SharedPreferences preferences = context.getSharedPreferences(MainActivity.sharedPrefs, Context.MODE_PRIVATE);
        SharedPreferences.Editor editPrefs = preferences.edit();
        DateFormat date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.GERMANY);
        Date dat = new Date();
        Log.d("TRIGGERDATE",date.format(dat));
        editPrefs.putString("REC", "Receiver called "+date.format(dat));
        editPrefs.commit();
    }
}

MainActivity.java

public static final String alarm = "com.example.aufgaben_planer.alarm";
private void registerMyAlarmBroadcast()
    {
        createPendingIntent();
        alarmManager.cancel(pendingIntent);
        alarmManager.cancel(PendingIntent.getBroadcast(this,0,new Intent(alarm),0));
        alarmManager.cancel(PendingIntent.getBroadcast(this,0,new Intent(alarm),PendingIntent.FLAG_CANCEL_CURRENT));
        alarmManager.cancel(PendingIntent.getBroadcast(this,0,new Intent(alarm),PendingIntent.FLAG_UPDATE_CURRENT));
        alarmManager.cancel(PendingIntent.getBroadcast(this,0,new Intent(this,MonthManager.class),PendingIntent.FLAG_UPDATE_CURRENT));
        alarmManager.cancel(PendingIntent.getBroadcast(this,0,new Intent(this,MonthManager.class),PendingIntent.FLAG_CANCEL_CURRENT));
        registerAlarmAt(3,0,0);
    }
    private void registerAlarmAt(int hour, int min, int sec){
        timingCal = Calendar.getInstance();
        timingCal.set(Calendar.HOUR_OF_DAY, hour); // At the hour you want to fire the alarm
        timingCal.set(Calendar.MINUTE, min); // alarm minute
        timingCal.set(Calendar.SECOND, sec); // and alarm second
        long intendedTime = timingCal.getTimeInMillis();
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, intendedTime,AlarmManager.INTERVAL_DAY, pendingIntent);
    }
    private void createPendingIntent(){
        Intent alarmIntent = new Intent(this, MonthManager.class);
        alarmIntent.setAction(alarm);
        pendingIntent = PendingIntent.getBroadcast( this, 0, alarmIntent,0 );
    }

Manifest.xml

<application> ...
        <receiver android:name=".MonthManager">
            <intent-filter>
                <action android:name="com.example.aufgaben_planer.alarm"></action>
            </intent-filter>
        </receiver>
</application>

另一个可能(或可能不)重要的说明: 我从不注销接收者(对我来说没有意义,因为我在清单中声明了它)

0 个答案:

没有答案