我想通过定期调用API来发送通知给用户,以检查是否有任何未决通知用户是否正在使用该应用程序。我想在后台运行该服务24小时。如何通过周期性地从Android后台服务调用api来发送通知
现在我通过报警管理
这里做任务是代码:
服务:
public class NotificationService extends IntentService {
public NotificationService() {
super("NotificationService");
}
@Override
protected void onHandleIntent(Intent intent) {
//call api
sendNotification();
}
private void sendNotification() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Hello")
.setContentText("Hello World")
.setAutoCancel(true);
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
playNotificationSound();
}
}
接收机
public class NotificationServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent dailyUpdater = new Intent(context, NotificationService.class);
context.startService(dailyUpdater);
}
}
AlarmManager
private void setRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
updateTime.setTimeZone(TimeZone.getDefault());
Intent downloader = new Intent(context, NotificationServiceReceiver.class);
downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 123546, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), REPEAT_TIME, pendingIntent);
}
的问题是,报警管理器没有工作,有时,当我再次启动应用程序,然后它的统计工作。
您是否考虑过使用来自服务器的推送通知,而不是轮询来自客户端的通知? –
还没有..我们需要根据用户登录凭证提取通知。 – KousiK
如何确保您的闹钟管理器不工作?可能是您的接收器没有运行service.Please检查此。 – Rama