Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suspicious cast to AlarmManager for a ALARM_SERVICE

alarm

Does anyone have faced somthing like this?

Here is the scenario: I want to build a separate class, from where I can stop and start an alarm, via static methods. From the Activity classes, I want to call the methods from this class that I'm planning to build, but the point is that, even tough I'm planning to pass the Activity context to the static methods, when I pass "context" to my AlarmManager object, Android Studio is passing me the following information which is printed on the screen above and I have to admit, that I just can't the point of the message.

What am I missing? I have been looking on Google, but It seems that this situation here is not something so common.

IMPORTAT: Regarding the image above, I tried to use just the context (code below), without using getApplicationContext(), but it didn't worked as well...

Here is the code:

package com.mydomain.myapp;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;



public class AlarmManager {

    private static AlarmManager  alarm;
    private static PendingIntent pIntent;


    //start alarm
    public static void setAlarm(Context context, int alarmId, long alarmTime) {

        Intent startAlarmIntent;
        long beginAt  = SystemClock.elapsedRealtime() + 60 * 1000;
        long interval = 300000; // 5 minutes

        alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        startAlarmIntent = new Intent(context, AlarmBroadcastReceiver.class);
        pIntent = PendingIntent.getBroadcast(context, alarmId, startAlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, beginAt, interval, pIntent);

    }

    //stop alarm
    public static void stopAlarm(Context context, int id) {

        Intent stopAlarmIntent;

        alarm = (AlarmManager)  context.getSystemService(Context.ALARM_SERVICE);
        stopAlarmIntent = new Intent(context, AlarmBroadcastReceiver.class);
        pIntent = PendingIntent.getBroadcast(context, id, stopAlarmIntent, 0);
        alarm.cancel(pIntent);
        pIntent.cancel();

    }

}

Can anyone give a hand with this, please? Tks!

like image 476
codermx Avatar asked Feb 03 '26 07:02

codermx


1 Answers

You created a class named AlarmManager. This is not the same as Android's AlarmManager, and you are trying to cast the value returned by getSystemService() to your AlarmManager, not android.app.AlarmManager.

The simplest solution is to change the name of your class to be something else.

like image 148
CommonsWare Avatar answered Feb 05 '26 21:02

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!