targetSdkVersion을 26으로 앱을 개발 중입니다.
전에 낮춰서 개발한 앱들은 잘 되는데, 이 앱만 기존 코드로는 알람이 발생하지 않네요...
그래서 찾아보던 중 알람 리시버에서 바로 백그라운드 서비스를 돌리지 않고, Foreground Service를 실행 한 후 그 서비스에서 다시 백그라운드 서비스를 실행하고, 포어그라운드 서비스는 죽이는 방식을 찾아 적용했더니 알람으로 백그라운드 서비스 실행까지는 성공했습니다.
하지만 알람을 좀 간격을 두고 수행하여, 서비스가 죽은 후에 알람이 발생하게 하면, 서비스가 실행되지 않습니다.
그러다 앱을 실행하여 서비스가 실행되면, 그동안 발생하지 않았던 알람들이 연속으로 실행됩니다.
혹시나 포어그라운드 호출 루틴의 문제 인가 했는데, 서비스가 죽으면 아예 알람 리시버 부터 호출이 안됩니다.
어떻게 해야 할까요?
아래 제가 사용한 코드입니다.
알람설정 부분
public void setAlarm(){
Intent intent = new Intent(MyService.this, RestartReceiver.class);
intent.setAction(RestartReceiver.ACTION_SETARARM_SERVICE);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), RestartReceiver.REQUEST_CODE_UPDATE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
long trigerTime = System.currentTimeMillis();
trigerTime=lastUpdate+UpdateInterval;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigerTime, sender);
}
else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
am.setExact(AlarmManager.RTC_WAKEUP, trigerTime, sender);
}
else
am.set(AlarmManager.RTC_WAKEUP, trigerTime, sender);
}
알람 리시버
<receiver
android:name=".RestartReceiver"
android:process=".remote" >
<intent-filter>
<action android:name="RestartReceiver.setalarm" />
<data android:scheme="package"/>
</intent-filter>
</receiver>
static public final String ACTION_SETARARM_SERVICE = "RestartReceiver.setalarm";
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(ACTION_SETARARM_SERVICE)) {
setAlarm(context);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent i = new Intent(context, MyForegroundService.class);
i.putExtra("Alarm", REQUEST_CODE_UPDATE);
context.startForegroundService(i);
} else {
Intent i = new Intent(context, MyService.class);
i.putExtra("Alarm", REQUEST_CODE_UPDATE);
context.startService(i);
}
return;
}
}