我正在开发一个应用程序,通知我(通过播放铃声)电池电量已达到一定水平。级别是可配置的。为此,我创建了一个启动服务的活动,该服务又为ACTION_BATTERY_CHANGED
注册接收器。
MyActivity - >我的服务 - > MyBrodcastReceiver [ACTION_BATTERY_CHANGED] - > onReceive() - > if(Battery Level< = MyValue) - >播放铃声
只要屏幕打开,一切正常但是一旦手机被锁定并且屏幕熄灭或CPU休眠,广播接收器的onReceive
方法就不会被调用,当我再次解锁手机时,一切正常。我通过日志验证了这一点。
只有在手机屏幕开启时才会调用onReceive
ACTION_BATTERY_CHANGED
onReceive
方法,并在手机睡眠时停止播放?
我甚至尝试在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();
}
}
}
}
方法中使用唤醒锁,但这不起作用
[我正在测试ICS(4.0.4)]
{{1}}
答案 0 :(得分:0)
您应该为在后台运行的服务授予WAKE_LOCK权限,这样即使手机处于空闲状态或中断,您的服务也会继续运行。希望你得到它,如果不清楚,请告诉我
答案 1 :(得分:0)
最后我使用带有RTC_WAKEUP的Alarm Manager来解决这个问题。 http://developer.android.com/reference/android/app/AlarmManager.html