1
사용자가 선택한 간격으로 알림 표시가 필요한 앱을 개발 중입니다. 앱이 종료 된 경우에도 이러한 알림을 표시해야합니다. AlarmManager를 사용하여 반복 알림을 예약했습니다. 앱이 실행 중이거나 시도 중일 때 제대로 작동하지만 앱이 종료되면 작동하지 않습니다.앱이 실행되지 않아도 알림을 표시하는 방법
public static void setRecurringNotification(Context context, long scTime) {
System.out.println("Inside setRecurringNotification()");
Intent notificationIntent = new Intent(context,
NotificationReceiver.class);
pendingIntentNotification = PendingIntent.getBroadcast(context, 0,
notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
SystemClock.elapsedRealtime() + scTime, scTime,
pendingIntentNotification);
}// End of setRecurringAlarm()
는 아래 NotificationReceiver 클래스입니다 :
public class NotificationReceiver extends WakefulBroadcastReceiver {
public static void sendNotification(Context context, MyMessage msg) {
System.out.println("sendNotification(): " + msg.getId());
Uri soundUri = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(msg.getTitle())
.setSmallIcon(R.drawable.ic_launcher)
.setStyle(
new NotificationCompat.BigTextStyle().bigText(msg.getContent()))
.setContentText(msg.getContent())
.setSound(soundUri);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(1, mBuilder.build());
}// End of sendNotification
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Inside NotificationReceiver.onReceive...");
try {
new NotifyUser(context).execute();
}
catch (Exception ex) {
ex.printStackTrace();
}
setResultCode(Activity.RESULT_OK);
}
private class NotifyUser extends AsyncTask<Void, Void, String> {
private Context context;
public NotifyUser(Context context) {
this.context = context;
}
@Override
protected String doInBackground(Void... params) {
SQLHelper sqlHelper = new SQLHelper(context);
try {
MyMessage msg = sqlHelper.getRandomMyMessageFromDB();
if (null != msg)
sendNotification(context, msg);
}
catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
}
BroadcastReceiver가 필요하지 않습니까? 실제로 NotificationReceiver 클래스에서 Service를 호출 해 보았습니다. 하지만 예상대로 결과를주지 못했습니다. –
BroadcastReceiver 시스템 이벤트를 기반으로 일부 작업을 수행해야 할 경우 사용해야합니다. 기타 서비스는 충분할 것입니다. 공식 문서를 따라 서비스하십시오. 그것을 잘 이해하면 효과가 있습니다. 수백만 명의 개발자가 동일한 방법을 사용하고 있습니다. 나머지 동일한 예제를 얻으려면 몇 가지 링크를 게시 할 것입니다. – shivamDev