Use AlarmManager instead.
Register your service to run said action every second (from this question):
Intent myIntent = new Intent(context, MyServiceReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 1); // first time
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000, pendingIntent);
What you were trying to do is call sleep(1000) on the UI thread (the thread responsible for updating the user-facing UI changes). That is a big no-no on Android, as it makes your app appear to be unresponsive.
EDIT for clarification after user comment:
I don't know how you are setting buttonpressed
, but you probably want to use an OnTouchListener:
boolean shouldBeDoingThings = true;
writer = new FileWriter(timedata);
Button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
shouldBeDoingThings = true;
return true;
}
else if(event.getAction() == MotionEvent.ACTION_UP){
shouldBeDoingThings = false;
return true;
}
return false;
}
});
Then you use messages or intents to start the flow (with the AlarmReceiver sending a message to your Service to set shouldBeDoingThings
to true
).
After that, somewhere in your service, you can run:
class Task implements Runnable {
private long lastUpdatedTime;
public Task()
{
lastUpdatedTime = 0;
}
@Override
public void run() {
if(shouldBeDoingThings)
{
if(TIME - lastUpdatedTime > 1000)
{
writer.append(TIME);
writer.flush();
lastUpdatedTime = TIME;
}
}
}
}
}
All in all, always remember: never block the UI thread. This is applicable for most Mobile SDKs today.
Hope I cleared things up for you.