I am new on Android. I am trying to create an application that uses BroadcastReceiver
to execute a function on the main activity triggered by a repeating alarm. I read that I had to dynamically register the broadcastReceiver
which I did - this is to be able to execute the function on the main activity. The problem I am faced with is that as soon as the app is exited, the alarm
stops working. I read that this is by design - is there a way to overcome this or do I have to use a service
? Thanks in advance.
Sample code:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "from AlarmReceiver", Toast.LENGTH_SHORT).show();
}
}
public class MainActivity extends AppCompatActivity {
private PendingIntent pendingIntent;
private AlarmManager manager;
private AlarmReceiver myReceiver = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceiver = new AlarmReceiver();
IntentFilter myIntentFilter = new IntentFilter("ANY_ACTION");
registerReceiver(myReceiver, myIntentFilter);
Intent myIntent = new Intent();
myIntent.setAction("ANY_ACTION");
pendingIntent = PendingIntent.getBroadcast(this, 0,myIntent,0);
}
public void startAlarm(View view) {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 1500;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_LONG).show();
}
}
I think, the reason why your alarm stops working when your app isn't running is that you're registering your AlarmReceiver locally with
registerReceiver
. If you want to register your AlarmReceiver so that it keeps working even when your app isn't running, you need to register it insideAndroidManifest.xml
.Firstly, add your reciever into
AndroidManifest.xml
like this:And set your alarm like this (Remember: Don't set alarm interval too short, set at least 1 minute; you set ur interval 1,5 second in ur code - it may not work):
And just do what you want to do when alarm triggers inside onRecieve: