Android关闭和打开屏幕

时间:2013-04-03 10:48:05

标签: android screen wakelock powermanager

我已经做了一个简单的应用程序,一旦按下按钮就打开和关闭屏幕,代码不会出现任何错误,但它没有做任何事情。这是代码:

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.button1);

    button.setOnClickListener(new View.OnClickListener() {

        @SuppressLint("Wakelock")
        @Override
        public void onClick(View arg0) {

            Log.d(TAG,  String.valueOf(screenWakeLock));

        if (screenWakeLock != null) {

                   if(screenWakeLock.isHeld())
                        Log.d(TAG, "wavelock held");
                      screenWakeLock.release();
                   screenWakeLock = null;

        }else{

            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            screenWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,   "screenWakeLock");
            screenWakeLock.acquire();
            Log.d(TAG,  String.valueOf(screenWakeLock));

                }

        }

    });


}

以及清单文件中的权限:

<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.DEVICE_POWER"></uses-permission>

没有错误,但屏幕上没有任何反应。有谁知道为什么?

提前谢谢!

1 个答案:

答案 0 :(得分:-1)

在另一个问题中:

Programmatically switching off Android phone

我找到了一种有效的方法。生根后你打电话:

try {
      Process proc = Runtime.getRuntime()
                .exec(new String[]{ "su", "-c", "reboot -p" });
      proc.waitFor();
} catch (Exception ex) {
      ex.printStackTrace();
}