我正在构建一个简单的应用程序,它BroadcastReciever
可以监听 PHONE_STATE:
<receiver android:name=".PhoneStateBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
在BroadcastReciever
'sonRecieve()
我在状态为时启动服务OFFHOOK
并在状态为时停止服务IDLE
:
public class PhoneStateBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
context.startService(new Intent(context, ProximityService.class));
}
else if(state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
context.stopService(new Intent(context, ProximityService.class));
}
}
}
在服务中,我正在注册接近传感器侦听器,并创建一个WakeLock
以便在通话时屏幕会很好地关闭。通话结束后,我停止服务,并在其中onDestroy()
取消注册侦听器并释放WakeLock
. 但似乎有些东西没有在那里发布,因为我看到我的应用程序消耗了巨大的电池电量(30%)。
我在监听器注销时和WakeLock
发布时都放了一个日志,我可以看到它WakeLock
被释放并且监听器被成功地取消注册(我也可以看到监听器被取消注册的日志SensorManager
)。
我在这里想念什么?这真的很烦人。
该服务的一些代码:
public int onStartCommand(Intent intent, int flags, int startId){
Log.d("CALL", "Service started");
// Get an instance of the sensor service, and use that to get an instance of
// a particular sensor.
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
mAudioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
mPowerMngr = (PowerManager) getSystemService(Context.POWER_SERVICE);
try{
mWakeLock = mPowerMngr.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, "Proximity");
if (!mWakeLock.isHeld()) {
Log.d("CALL", "Wake lock acquired");
mWakeLock.acquire();
}
}
catch (Exception e){
mWakeLock = null;
}
return START_STICKY;
}
public void onDestroy(){
super.onDestroy();
mSensorManager.unregisterListener(this);
if (mWakeLock != null) {
if (mWakeLock.isHeld()) {
Log.d("CALL", "Wake lock released");
mWakeLock.release();
}
}
Log.d("CALL", "Service stopped");
}
我看到的日志:
09-30 03:35:09.120: D/SensorManager(21565): unregisterListener:: disable all sensors for this listener, listener = com.eladaharon.android.proximity.ProximityService@41a31a18
09-30 03:35:09.125: D/CALL(21565): Wake lock released
09-30 03:35:09.125: D/CALL(21565): Service stopped
非常感谢!埃拉德