我正在开发一个应用程序,它将通知我(通过播放铃声)电池电量已达到一定水平。级别是可配置的。为此,我创建了一个启动服务的活动,该服务又为ACTION_BATTERY_CHANGED
.
MyActivity -> MyService -> MyBrodcastReceiver [ACTION_BATTERY_CHANGED] -> onReceive() -> if(Battery Level <= MyValue) -> 播放铃声
只要屏幕打开,一切都会正常工作,但是一旦手机被锁定并且屏幕关闭或 CPU 休眠,广播接收器的onReceive
方法就不会被调用,当我再次解锁手机时,一切正常。我通过日志记录验证了这一点。
是否仅在手机屏幕打开时才调用该onReceive
方法ACTION_BATTERY_CHANGED
并在手机睡眠时停止?
我什至尝试在onReceive
方法中使用唤醒锁定,但没有奏效</p>
[我正在使用 ICS (4.0.4) 进行测试]
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
public class BatteryMeterService extends Service {
private BatteryStatusReceiver batteryStatusReceiver;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryStatusReceiver = new BatteryStatusReceiver(null);
registerReceiver(batteryStatusReceiver, intentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(batteryStatusReceiver);
}
}
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import com.amol.bm.BatteryMeterUtility.NotificationInfo;
public class BatteryStatusReceiver extends BroadcastReceiver {
private BatteryMeterUtility batteryMeterUtility;
public BatteryStatusReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float fPct = (level / (float)scale) * 100;
int levelPct = (int)fPct;
boolean prefAlertLowBattery = sharedPrefs.getBoolean("prefAlertLowBattery", true);
if(prefAlertLowBattery) {
String prefAlertLowBatteryValue = sharedPrefs.getString("prefAlertLowBatteryValue", "20");
int lowBatteryValue = Integer.parseInt(prefAlertLowBatteryValue);
if(levelPct <= lowBatteryValue && iStatus != BatteryManager.BATTERY_STATUS_CHARGING) {
notificationInfo.icon = R.drawable.low_battery;
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "BM WakeLook");
wakeLock.acquire();
batteryMeterUtility.playAlertRingtone(alertRingtone);
wakeLock.release();
}
}
}
}