My app contains an activity which UI has to be updated due to server show schedule. What is the best approach for updating UI in this situation.
So far, I’ve come up with AlarmManager and Service but I’m not sure it’s a good practice. Any other suggestions ? I’ve seen some relevant methods in Handler but I’m not how to use them regarding the uptime parameter.
Alarm
Intent intent = new Intent(getActivity(), OnAirUpdateAlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(getActivity(),
0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
Receiver (checks whether the running activity is one the needs to updated)
@Override
public void onReceive(Context context, Intent intent) {
ActivityManager am = (ActivityManager) context
.getSystemService(Activity.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
String name = taskInfo.get(0).topActivity.getShortClassName();
if (name.equals(".activity.handset.HandsetMainActivity")) {
Intent notificationIntent = new Intent(context,
HandsetMainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.putExtra(
context.getResources().getString(
R.string.extras_main_activity_on_new_intent),
HandsetMainActivity.UPDATE_PLAYER_FRAGMENT_UI);
context.startActivity(notificationIntent);
}
}
And if it is – requests fragments UI update. Again not sure if this is the best solution.
Thanks for your suggestions.
Well, you know when your application is visible ‘onStart() / onStop()’ at this point you can start a
TimerTask.I guess if you are only updating the UI it doesn’t have to happen when the user doesnt have your app opened.