i'm using alarm manger to set and alarm that's go off in exact time in day using service but it only run the mediaplayer for 3 sec and terminate the service , if i swipe the app while alarm song is running the service terminate
// when i used TimePicker instead of setting time by myself the alarm goes off immediately for 3 sec then stops and in the exact time that i picked using TimePicker the alarm works perfectly
<manifest
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service
android:name=".Service"
android:exported="false" />
service
public class Service extends android.app.Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.rev);
mediaPlayer.start();
return START_STICKY;
}
}
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2018);
calendar.set(Calendar.MONTH, 2);
calendar.set(Calendar.DAY_OF_MONTH, 24);
calendar.set(Calendar.HOUR_OF_DAY, 1);
calendar.set(Calendar.MINUTE, 4);
calendar.set(Calendar.SECOND, 0);
setAlarm(calendar.getTimeInMillis());
}
private void setAlarm(long time) {
Intent i = new Intent(this, Service.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, i, 0);
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int ALARM_TYPE = AlarmManager.RTC_WAKEUP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
am.setExactAndAllowWhileIdle(ALARM_TYPE, time, pendingIntent);
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
am.setExact(ALARM_TYPE, time, pendingIntent);
else
am.set(ALARM_TYPE, time, pendingIntent);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
}
You should start the service as a foreground service with startForeground(<notification id>, <notification>)
in your onStart()
method. Then it will have higher priority and is less likely to be killed. See startForeground.