I want to make an application that can update automatically by time when some method excuted. I used Handler to make it update automatically by time. when the time has come, it will update data to firebase. it can work when the app is not closed. but when i closed the app before the specified update time, the handler does not work. Although I've used Services that work to keep the application running.
so far this is my code :
AutoUpdate.java
public class AutoUpdate extends AppCompatActivity {
TextView textDateTime;
TextView textcurrentDateTime;
DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_update);
String currentDate = DateFormat.getDateTimeInstance().format(new Date());
textcurrentDateTime.setText(currentDate);
final Handler handler=new Handler();
final Runnable updateTask=new Runnable() {
@Override
public void run() {
updateCurrentTimeToFirebase();
handler.postDelayed(this,7000);
handler.removeCallbacks(this);
}
};
handler.postDelayed(updateTask,7000);
startService(new Intent(this, MyService.class));
}
public void updateCurrentTimeToFirebase() {
String currentDate = DateFormat.getDateTimeInstance().format(new Date());
mDatabase = FirebaseDatabase.getInstance().getReference();
String id = mDatabase.push().getKey();
mDatabase.child("autoUpdate").child(id).child("updateTime").setValue(currentDate);
}
}
Myservice.java
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
}
please i need your help.. Thankyou so much..