Alarm Manager Example
This is working code. It wakes CPU every 10 minutes until the phone turns off.
Add to Manifest.xml:
...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver android:process=":remote" android:name=".Alarm"></receiver>
...
Code in your class:
package yourPackage;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public class Alarm extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void setAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
public void cancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Set Alarm from Service:
package yourPackage;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class YourService extends Service
{
Alarm alarm = new Alarm();
public void onCreate()
{
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
alarm.setAlarm(this);
return START_STICKY;
}
@Override
public void onStart(Intent intent, int startId)
{
alarm.setAlarm(this);
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
If you want to set alarm repeating at phone boot time:
Add permission and the service to Manifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
...
<receiver android:name=".AutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
...
<service
android:name=".YourService"
android:enabled="true"
android:process=":your_service" >
</service>
And create a new class:
package yourPackage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AutoStart extends BroadcastReceiver
{
Alarm alarm = new Alarm();
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
alarm.setAlarm(context);
}
}
}
I tried the solution from XXX and while it did initially work, at some point it stopped working. The onReceive
never got called again. I spent hours trying to figure out what it could be. What I came to realize is that the Intent
for whatever mysterious reason was no longer being called. To get around this, I discovered that you really do need to specify an action for the receiver in the manifest. Example:
<receiver android:name=".Alarm" android:exported="true">
<intent-filter>
<action android:name="mypackage.START_ALARM" >
</action>
</intent-filter>
</receiver>
Note that the name is ".Alarm"
with the period. In XXX's setAlarm
method, create the Intent
as follows:
Intent i = new Intent("mypackage.START_ALARM");
The START_ALARM
message can be whatever you want it to be. I just gave it that name for demonstration purposes.
I have not seen receivers defined in the manifest without an intent filter that specifies the action. Creating them the way XXX has specified it seems kind of bogus. By specifying the action name, Android will be forced to create an instance of the BroadcastReceiver
using the class that corresponds to the action. If you rely upon context, be aware that Android has several different objects that are ALL called context and may not result in getting your BroadcastReceiver
created. Forcing Android to create an instance of your class using only the action message is far better than relying upon some iffy context that may never work.
Here's a fairly self-contained example. It turns a button red after 5sec.
public void SetAlarm()
{
final Button button = buttons[2]; // replace with a button from your own UI
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive( Context context, Intent _ )
{
button.setBackgroundColor( Color.RED );
context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
}
};
this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );
PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
// set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent );
}
Remember though that the AlarmManager fires even when your application is not running. If you call this function and hit the Home button, wait 5 sec, then go back into your app, the button will have turned red.
I don't know what kind of behavior you would get if your app isn't in memory at all, so be careful with what kind of state you try to preserve.
MainActivity.java
package com.example.alarmexample;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAlert();
} public void startAlert() {
int timeInSec = 2;
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (timeInSec * 1000), pendingIntent);
Toast.makeText(this, "Alarm set to after " + i + " seconds",Toast.LENGTH_LONG).show();
}
}
MyBroadcastReceiver.java
package com.example.alarmexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
@Override
public void onReceive(Context context, Intent intent) {
mp=MediaPlayer.create(context, R.raw.alarm);
mp.start();
Toast.makeText(context, "Alarm", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarmexample" >
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.alarmexample.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyBroadcastReceiver" >
</receiver>
</application>
</manifest>