Reputation: 20906
I have a service which checks if the phone is ringing. In this service I am also checking if the phone is turned around or not. Is it good to running this sensor check all the time while service is running or this is to much for battery and CPU resources?
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
boolean turnAroundToStop = some code is executed
if (turnAroundToStop) {
float value = Math.abs(event.values[1]);
if (value > orientationLim && !stopped) {
// Down
do some code
stopped = true;
} else {
// Up
stopped = false;
}
}
}
}
Upvotes: 1
Views: 378
Reputation: 13957
Running the service all the time is expensive regarding CPU and battery. There are two options that I know which might help you to reduce the CPU load and I'd recommend to use them if possible.
Option 1: stop service when display turns off and start service, when the display turns on. You can achieve this by using an BroadcastReceiver
:
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// stop service
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// start service
}
}
}
Important: register the event programmatically:
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver receiver = new ScreenReceiver();
registerReceiver(receiver, filter);
Option 2: use an AlarmManager
instead: this option is better if your sensor checks need to be performed also during standby of the device. However, the downside is that it is not a good option for short intervals (lets say smaller than 30 minutes).
public void SetAlarm(Context context) {
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 *60 , pendingIntent);
}
You probably need this in the manifest:
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
Note: these are not full/running examples. The code fragments should help you to start with the right keywords. Hope this helps anyway ... Cheers!
Upvotes: 2