Reputation: 471
I am writing an app that when battery reach some level the wifi will automatically shut done, my app works fine while screen is on, but it not do anything when the screnn is lock.
My app is like, start activity, user click the button to start the Service, the service will register the broadcastreceiveer to get the current level of battery, and braodcastreceiver will see if battery level reach the limit and decide to shut done wifi or not
I have try use isScreenOn() to find whether screen is on or off, but this also not work
here is my code
public class BatteryMonitor extends Service {
/*declear variables*/
private BroadcastReceiver batteryReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
/* get battery level*/
//Check is screen is on or not
boolean isScreenOn = powermanager.isScreenOn();
//set as 90 just for test function//
if(batteryLevel<=90){
if(isScreenOn==true){
if(isCharging == true && wifimanager.isWifiEnabled()){
//not do anything
}else if(isCharging == false && wifimanager.isWifiEnabled()){
wifimanager.setWifiEnabled(false);
}
}else{
if(isCharging == true && wifimanager.isWifiEnabled()){
//not do anything
}else if(isCharging == false && wifimanager.isWifiEnabled()){
wifimanager.setWifiEnabled(false);
}
}
}
}
};
public void onStart(Intent intent, int startId) {
wifimanager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
powermanager = (PowerManager) getSystemService(Context.POWER_SERVICE);
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
};
@Override
public IBinder onBind(Intent i) {
// TODO Auto-generated method stub
return null;
}
}
Upvotes: 2
Views: 256
Reputation: 27549
Create a Separate class for Receiver, register it into Manifest file for Battery change action. Then it will work even when screen is off.
Broadcast Receiver read this link.
You need to sendBroadcast when you want to send a message to Receiver, make sure that you added proper Action String , in manifest for Receiver ,
Upvotes: 3