Reputation: 83
I want to make an timer which starts counting when the Android device is woken up and stops when the Android device is set to sleep. I found nothing, how a activity could be triggered by wake up/sleep.
I hope you can help me with my problem
Upvotes: 5
Views: 9671
Reputation: 1056
Use BroadcastReceiver
and service to catch Screen_on and_off.... For example like ...
public class InternetReceiver extends BroadcastReceiver{
private boolean screenOff;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, InternetService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
Upvotes: 1
Reputation: 83
I used a BroadcastReceiver like timonvlad said but ACTION_SCREEN_ON and ACTION_SCREEN_OFF could not be called by XML so I created an service. The service has to be registered in the XML then I used this code
public class OnOffReceiver extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//This happens when the screen is switched off
}
}, new IntentFilter(Intent.ACTION_SCREEN_OFF));
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//This happens when the screen is turned on and screen lock deactivated
}
}, new IntentFilter(Intent.ACTION_USER_PRESENT));
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
Upvotes: 1
Reputation: 665
Set up repeating event that will be fired when the device is awake:
AlarmManager.setRepeating(AlarmManager.RTC, time, period, pendingIntent);
Then catch those alarms and increment your timer counter, it will be counting when device is awake.
Don't start activity when device wakes up. Users will not be happy about such behavior of an app. Use notifications instead.
Upvotes: 0
Reputation: 12487
You should create a BroadcastReceiver that listens to the ACTION_BOOT_COMPLETED intent. In the implementation, you have to store the timestamp of when that intent was received.
After that, you can create an activity that retrieves that timestamp, and calculates how much time has the phone been running.
Upvotes: 0