During my development of a small android app, I have a problem to get an alarm manager running when the app is terminated by the user. While when the app is running in the foreground or background everything works fine.
I have done the following steps:
AndroidManifest.xml
<receiver android:name="MyBroadcastReceiver" ></receiver>
MainActivity.java
Within the OnClick method of a button I call
startAlert( x*60*1000);
x is a class-wide visible variable
public void startAlert(long timeInMillis){
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() (timeInMillis),pendingIntent);
}
Toast.makeText(this, "Alarm in " x " Minuten",Toast.LENGTH_LONG).show();
}
MyBroacastReciever.java
public void onReceive(Context context, Intent intent) {
MediaPlayer player = MediaPlayer.create(context,MainActivity.link);
player.start();
Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();}
What can I do to get the alarmManager
sucessfully running, when the app is closed?
CodePudding user response:
You could put the alarm manager in the service. The foreground service is used to keep our application alive even though the main application has been quit by the user. And then the alarm manager could trigger the code in the broadcast receiver class
CodePudding user response:
Ok i will give this a chance. Is it also necessary to migrate the intent and pending indent in the broadcastreceiver?