我想通過定期調用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