I am new to android programming. What am i doing wrong? AlarmReceiver class not triggering...I want to trigger repeatedly the AlarmReceiver.class ...
I used the code from this page https://developer.android.com/training/scheduling/alarms#precision
OnCreate at MainActivity.java i have the following code
AlarmManager alarmManager = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this,AlarmReceiver.class);
//Check if the PendingIntent already exists
PendingIntent pendingIntent =
PendingIntent.getService(this, 6661, intent,
PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null && alarmManager != null) {
//cancel here if you want
}
//Run every 60 seconds!
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60000,
60000, pendingIntent);
The AlarmReceiver.java class includes the following code...
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Log.i("logit","testing...");
}
}
Do you have an entry in your manifest for the receiver like that?
<receiver android:name=".AlarmReceiver"></receiver>
Related
I have searched in everywhere but I can understand because my Service at a specific time of the day don't fire. Nothing happens.
My code for set up the Alarm:
AlarmManager alarmMgr = (AlarmManager) act.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(act, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(act, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// set for 5 seconds later
alarmMgr.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis()+5000, alarmIntent);
My code for the Service:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Alarm worked well");
Utils.criarNotificacao(context);
}
}
In the Manifest:
<receiver android:name="br.com.blacktoad.q48h2.utils.AlarmReceiver" android:process=":remote"></receiver>
I can't find any answer.
I find the error!
I need put the:
<receiver android:name="br.com.blacktoad.q48h2.utils.AlarmReceiver" android:process=":remote"></receiver>
in the manifest, but contained in the "application" tag
I have class for call myService with alaram Manager. From mainActivity this is my code to set alarm manager.
Intent downloader = new Intent(context, AlarmReceiver.class);
downloader.putExtra("limit", limit.getSelectedItem().toString());
downloader.putExtra("delay",perMin.getSelectedItem().toString());
downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); `pendingIntent = PendingIntent.getBroadcast(context, 0, downloader,PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int delay = Integer.parseInt(perMin.getSelectedItem().toString());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,10 * 1000, delay * 1000, pendingIntent);
and here my alarm receiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent update = new Intent(context, IntervalService.class);
Log.i(tag, "Call service from Alaram Receiver");
context.startService(update);
}}
I know when i want to cancel alarm manager from main activity easily call alarmManager.cancel(pendingIntent) but i want to cancel alarm manager to complete my service task and after that set again like as above.
Just modified your code,
public void setAlarmManager(boolean cancel){
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,downloader,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int delay = Integer.parseInt(perMin.getSelectedItem().toString());
if(!cancel)
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,10 * 1000, delay * 1000, pendingIntent);
else
alarmManager.cancel(pendingIntent);
}
call this function when needed,
to Start: setAlarmManager(false);
to Cancel: setAlarmManager(true); //Call this function in Service
Try, this may work. Thanks.
Application need synchronize data from server in interval (for example every 30min) or manually on background. Result is saved to local database. After sync is done I want remind activity/fragment ... and force update list (if needed). There are many activities, so I want move it outside of activity and make it more consistent.
For now I created AsyncTask which get result from server and save to DB.
What shoud I use? BroadcastReciever, Service, AlarmManager?
UPDATE
Based on answers I start alarm in Application
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
manager.setInexactRepeating(AlarmManager.RTC, 0, AlarmManager.INTERVAL_HALF_HOUR, pendingIntent);
Created Receiver
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent syncIntent = new Intent();
syncIntent.setClass(context, DataSyncer.class);
startWakefulService(context, syncIntent);
}
}
Created IntentService
public class DataSyncer extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
// get data from server
// save to DB
AlarmReceiver.completeWakefulIntent(intent);
}
}
And registered Receiver and Service in AndroidManifest
<service
android:name="com.cloudit.tsystems.app.DataSyncer"
android:enabled="true">
</service>
<receiver
android:name="com.cloudit.tsystems.app.AlarmReceiver"
android:enabled="true">
</receiver>
Where and how I notify that sync is done in Activity/Fragment?
I would use the AlarmManager and register a BroadcastReceiver. Once the receiver is fired, I will launch an IntentService to download the data in the background.
Configure your alarm:
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyBroadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
manager.setInexactRepeating(AlarmManager.RTC, 0, AlarmManager.INTERVAL_HALF_HOUR, pendingIntent);
Create a BroadcastReceiver that will get notified when the alarm goes off. Note that I'm using a WakefulBroadcastReceiver so that the device doesn't go to sleep when you're syncing.
class MyBroadcast extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent syncIntent = new Intent();
syncIntent.setClass(context, DataSyncer.class);
startWakefulService(context, syncIntent);
}
}
Next, an IntentService that will download data in the background:
class DataSyncer extends IntentService{
...
#Override
protected void onHandleIntent(Intent intent) {
//sync data
MyBroadcast.completeWakefulIntent(intent);
}
}
Update:
So now that you have your data synced, there are several options to notify Activities and Fragments. You can use a LocalBroadcastManager to broadcast. Take a look at this link for more details.
Use an AlarmManager to trigger a PendingIntent on a 30 minute interval that starts an IntentService to do your download.
Intent intent = new Intent(context, PollingService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(
AlarmManager.RTC,
System.currentTimeMillis(),
AlarmManager.INTERVAL_HALF_HOUR,
pendingIntent
);
When the IntentService is done updating your data, it can send a Broadcast that your Activity/Fragment has registered to listen for to notify it of new data and refresh it's view.
sendBroadcast(new Intent("DATA_UPDATED"));
In your Fragment
getActivity().registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//update UI
}
}, new IntentFilter("DATA_UPDATED"));
I have code which is to be run daily; for this I'm trying to use AlarmManager. This is my code for triggering alarms:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this, AlarmReciever.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pi); // cancel any existing alarms
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, pi);
}
This part of the code is calling AlarmReciever class as expected, but I want the code in the AlarmReciever class to be executed only once daily. It's being called multiple times. How do I restrict it?
This is the AlarmReciever class:
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("in alarm reciever class");
}
}
I'm trying to perform some business logic in the onReceive() method.
In the manifest.xml file:
<receiver android:name="com.xyz.reciever.AlarmReciever"></receiver>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
are declared.
I believe the code you should be using to set your alarm would be this:
Intent i = new Intent(this, AlarmReciever.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); // <- HERE!!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pi); // cancel any existing alarms
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, pi);
since your AlarmReciever is a BroadcastReceiver. Use PendingIntent.getBroadcast().
If you have much work to do in your receiver's onReceive() method, you might also delegate it to an IntentService. See this answer if you decide to do that.
I have a Service "GroupsTaskAlarmChecker" that is called every 20 seconds by AlarmManager in onCreate of Groups.class activity this way:
int seconds = 20;
Intent myIntent = new Intent(Groups.this, GroupsTaskAlarmChecker.class);
pendingIntent = PendingIntent.getService(Groups.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), seconds * 1000, pendingIntent);
This works perfectly. But I need to do that when device boot.
Then I know I have to make AndroidManifest like this:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".ReceiverBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
<category android:name="android.intent.category.HOME">
</category></action></intent-filter>
</receiver>
and then mi broadcastReceiver like this:
public class ReceiverBoot extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int seconds = 20;
Intent myIntent = new Intent(context, GroupsTaskAlarmChecker.class);
pendingIntent = PendingIntent.getService(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), seconds * 1000, pendingIntent);
}
}
but inside this onReceive I dont know how can I do the same that I did before (with intent and alarmManager to start the service each 20 seconds).
Error in this line:
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Is possible that I can't make an AlarmManager inside BroadcastReceiver?
I thank you all, I am an Android begginer and I need your help. Sorry for my english ;)
To summarize the answers and comments above: the onReceive handler receives a context which can be used to access getSystemService and ALARM_SERVICE. Sample code:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Start periodic service.
Calendar cal = Calendar.getInstance();
Intent srvIntent = new Intent(context, MyService.class);
PendingIntent pIntent = PendingIntent.getService(context, 0, srvIntent, 0);
// Use context argument to access service
AlarmManager alarm =
(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Repeat every 5 seconds
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
5000, pIntent);
}
}
}
Create a new class with this code and of course change MyReceiver and MyService to the names in your implementation.
ALARM_SERVICE is neither defined in the class ReceiverBoot nor in BroadcastReceiver.
You should reference Context.ALARM_SERVICE as the argument for getSystemService(String).
Here is a little contribution, which I believe that can add a more complete vision about achieving the goal of this question.
First: configure a "receiver" inside of the AndroidManifest from your app.
<receiver
android:name=".AlarmBroadcastReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Second: with a Class that EXTENDS the Abstract Class BroadcastReceiver, you should determine if the Intent Action was "BOOT_COMPLETED". If the condition is satisfied, you can call a method from your class which has all the construction to your Alarm.
See the following snippet bellow.
public class AlarmBroadcastReceiver extends BroadcastReceiver {
String TAG = "ALARMS";
String CLASS = this.getClass().getSimpleName() + ": ";
Context alarmContext;
#Override
public void onReceive(final Context context, Intent intent) {
Log.d(TAG, CLASS + "[START] onReceive()... ");
alarmContext = context;
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Log.d(TAG, CLASS + "BOOT_COMPLETED action has been received.");
setAlarmOnBoot();
}
Log.d(TAG, CLASS + "[END] onReceive()... ");
}
public void setAlarmOnBoot() {
Log.d(TAG, CLASS + "[START] - setAlarmOnBoot()");
final long beginAt = SystemClock.elapsedRealtime() + 60 * 1000;
final long interval = 300000; // 5 minutes
try {
AlarmManager alarm = (AlarmManager) alarmContext.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(alarmContext, AlarmBroadcastReceiver.class);
PendingIntent pIntent = PendingIntent.getService(alarmContext, 0, intent, 0);
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, beginAt, interval, pIntent);
Log.d(TAG, CLASS + "the Alarm has been configured successfully (5 minutes) of interval.");
} catch (Exception e) {
Log.d(TAG, CLASS + "an exception has ocurred while setting the Alarm...");
e.printStackTrace();
}
Log.d(TAG, CLASS + "[END] - setAlarmOnBoot()");
}
}
in your onReceive:
if ("android.intent.action.BOOT_COMPLETED".equals (intent.getAction())){
//start it again here
}