我必须制作一个使用唤醒锁使屏幕保持打开状态的应用程序。我有两个按钮,一个用于打开唤醒锁,另一个用于将其关闭。
打开唤醒锁的按钮可以正常工作,但是关闭唤醒锁的按钮会使应用程序在按下时崩溃。
这是代码:
public class MainActivity extends ActionBarActivity {
@Override @SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupScreenONButton();
setupScreenOFFButton();
}
@SuppressWarnings("deprecation")
private void setupScreenOFFButton() {
Button ScreenOffButton = (Button) findViewById(R.id.buttonScreenOFF);
ScreenOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"Screen OFF");
wl.release();
Toast.makeText(MainActivity.this, "Screen OFF", Toast.LENGTH_SHORT).show();
}
});
}
@SuppressWarnings("deprecation")
private void setupScreenONButton() {
Button ScreenOnButton = (Button) findViewById(R.id.buttonScreenON);
ScreenOnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,"Screen ON");
wl.acquire();
Toast.makeText(MainActivity.this,"Screen ON", Toast.LENGTH_SHORT).show();
}
});
}
关于我在做什么错的任何想法吗?
谢谢
最佳答案
您需要释放之前获得的同一Wakelock,而不要获取新的Wakelock。
编辑:添加代码(未试用):
public class MainActivity extends ActionBarActivity {
PowerManager.WakeLock wl;
@Override @SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"Screen OFF");
setContentView(R.layout.activity_main);
setupScreenONButton();
setupScreenOFFButton();
}
@SuppressWarnings("deprecation")
private void setupScreenOFFButton() {
Button ScreenOffButton = (Button) findViewById(R.id.buttonScreenOFF);
ScreenOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
wl.release();
Toast.makeText(MainActivity.this, "Screen OFF", Toast.LENGTH_SHORT).show();
}
});
}
@SuppressWarnings("deprecation")
private void setupScreenONButton() {
Button ScreenOnButton = (Button) findViewById(R.id.buttonScreenON);
ScreenOnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
wl.acquire();
Toast.makeText(MainActivity.this,"Screen ON", Toast.LENGTH_SHORT).show();
}
});
}