Dim
Dim

Reputation: 4807

Alarm not firing in Android

my alarm is not firing at all.

MainActivity:

    final Context context = this;

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 13);
    calendar.set(Calendar.MINUTE, 30);

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

    AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, alarmIntent);

AlarmReceiver:

public class AlarmReceiver extends BroadcastReceiver {

    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";

    @Override
    public void onReceive(Context context, Intent intent) {

        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        notificationManager.notify(id, notification);

    }
}

Manifest:

    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.SET_ALARM"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".AlarmReceiver" />
    </application>

</manifest>

Using: compileSdkVersion 25 minSdkVersion 23 targetSdkVersion 25

Upvotes: 0

Views: 245

Answers (1)

aj0822ArpitJoshi
aj0822ArpitJoshi

Reputation: 1182

For API 23 and above you can use setAndAllowWhileIdle():

So change your code to:

if (Build.VERSION.SDK_INT >= 23)
        alarmManager. setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent); 
else if (Build.VERSION.SDK_INT >= 19)
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
else if (Build.VERSION.SDK_INT >= 16)
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), 1 * 1000 * 60 * 60 * 24, pendingIntent);

and check if is it working or not.

Upvotes: 2

Related Questions