我需要帮助来停止服务中的WakeLock。这是我尝试过的:
public class SensorSevice extends Service implements SensorEventListener {
Sensor registerListener;
SensorManager sensorManager;
private PowerManager powerManager;
private PowerManager.WakeLock wakeLock;
private int field = 0x00000020;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.values[0] == 0) {
Toast.makeText(this,"Close",Toast.LENGTH_SHORT).show();
wakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
wakeLock.acquire();
}else {
Toast.makeText(this,"Far",Toast.LENGTH_SHORT).show();
powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
wakeLock.acquire();
}
wakeLock.release();
}
@Override
public void onDestroy() {//here u should unregister sensor
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
sensorManager.unregisterListener(this);
}
@Override//here u should register sensor and write onStartCommand not onStart
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
registerListener = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
sensorManager.registerListener(this, registerListener, SensorManager.SENSOR_DELAY_NORMAL);
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(field, "aa");
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent bIntent = new Intent(SensorSevice.this, MainActivity.class);
PendingIntent pbIntent = PendingIntent.getActivity(SensorSevice.this, 0, bIntent, 0);
NotificationCompat.Builder bBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("Title")
.setContentText("Subtitle")
.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pbIntent);
Notification barNotif = bBuilder.build();
this.startForeground(1, barNotif);
return Service.START_STICKY;
}
}
当我在Jellybean设备中使用它时,它可以工作。问题是它在Nougat设备中不起作用。该服务不会关闭屏幕,但接近传感器工作。我错放了wakelock.release
?
该服务的参考位于here的另一个问题中。
谢谢。