我正在尝试了解服务和广播接收器。下面的代码是一个一直在后台运行的服务。问题是我不知道它会如何影响电池消耗。
我的目标是检测屏幕的开启和关闭,因此当应用程序关闭或打开时,我需要在后台运行服务......
它会消耗大量电池吗?你能解释一下吗?
谢谢
public class MyService extends Service{
private static final String TAG = "MyService";
private BroadcastReceiver mScreenOnOffReceiver;
private BroadcastReceiver OnOffBroadcastReceiver;
private NotificationManager mNotificationManager;
private Notification barNotif;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// here to show that your service is running foreground
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent bIntent = new Intent(this, WidgetBroadCastReceiver.class);
PendingIntent pbIntent = PendingIntent.getActivity(this, 0 , bIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationCompat.Builder bBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("STICKY")
.setContentText("Sub Title")
.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pbIntent);
barNotif = bBuilder.build();
this.startForeground(1, barNotif);
// here the body of your service where you can arrange your reminders and send alerts
Thread mThread = new Thread() {
@Override
public void run() {
// Register the ScreenOnOffReceiver.java
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mScreenOnOffReceiver = new ScreenOnOffReceiver();
registerReceiver(mScreenOnOffReceiver, filter);
// initialize and register mScreenOnOffReceiver (no need the BroadcastReceiver class)
OnOffBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.e("", "SERVICE Screen is: " + "turned OFF.....");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.e("", "SERVICE Screen is: " + "turned ON......");
}
}
};
registerReceiver(OnOffBroadcastReceiver, new IntentFilter(filter));
}
};
mThread.start();
return START_STICKY;
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service has Started", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_SHORT).show();
unregisterReceiver(mScreenOnOffReceiver);
unregisterReceiver(OnOffBroadcastReceiver);
stopForeground(true);
}
}