Some app like calendar need to update when
system time change, we need to detect new day.
Declare variables.
int con = 0;
PendingIntent pi;
BroadcastReceiver
br;
AlarmManager am;
Create function like this.
private void setup() {
br = new
BroadcastReceiver() {
@Override
public void
onReceive(Context c, Intent i) {
//Update data
here.
}
};
registerReceiver(br, new IntentFilter("com.example.vidu"));
pi =
PendingIntent.getBroadcast(this, 0, new Intent("com.example.vidu"),0);
am =
(AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()
+ con, 86400000, pi);
}
In onCreate() we calculate wait time and
call function like this.
String p = new
Date().toString();
p = p.trim();
String a[] = p.split(" ");
String a1[] = a[3].split(":");
int b = Integer.parseInt(a1[0]);
int g = Integer.parseInt(a1[1]);
int g2 = Integer.parseInt(a1[2]);
int pu = b * 60 * 60 + g * 60+g2;
pu = pu * 1000;
con = 86400000 - pu;
setup();
Now when open app, alarm will run at 12 o’
clock at night, and after 24 hours mean next day it will run update again.
This way doesn’t affect battery because it
minimize check times.
Remember to declare service in file Manifest.xml
<service
android:name=".myservice"
android:enabled="true"
android:exported="false"
/>
And destroy when exit class.
@Override
protected void onDestroy() {
super.onDestroy();
am.cancel(pi);
unregisterReceiver(br);
}
No comments:
Post a Comment