0
我已經寫了一個android程序,其中包含按下音量按鈕時增加1的計數器。當按下此按鈕時,它也應該關閉屏幕,並在重新打開之前等待5秒鐘不活動。但是當我運行應用程序時,除了計數器增加之外沒有任何事情發生,即屏幕沒有關閉。按下音量按鈕時關閉屏幕
這裏是我的java類:
public class MainActivity extends Activity {
private TextView counterTextView;
int count;
PowerManager.WakeLock wakeLock;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counterTextView = (TextView) findViewById(R.id.counterTextView);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP && event.getRepeatCount() == 0) {
count++;
counterTextView.setText(" " + count + " ");
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakelockTag");
wakeLock.acquire();
new Handler().postDelayed(screenOnRunnable(), 5000);
return true;
}
return super.onKeyDown(keyCode, event);
}
private Runnable screenOnRunnable() {
return new Runnable() {
@Override
public void run() {
wakeLock.release();
}
};
}
}
我還添加了WAKE_LOCK權限在清單:
<uses-permission android:name="android.permission.WAKE_LOCK" />
我不知道什麼是錯的...任何幫助將不勝感激。
您沒有傳遞上下文,也沒有在創建訪問POWER_SERVICE時使用。 – Ali786 2015-04-04 11:35:27