屏幕关闭按钮单击

时间:2013-01-14 10:44:30

标签: android android-button

我想在按钮点击时打开设备的屏幕,我使用的代码如下

public class MainActivity extends Activity {

Button powerOff;
int amountOfTime =0;

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

powerOff = (Button)findViewById(R.id.button1);
powerOff.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);

        // Choice 1
        manager.goToSleep(amountOfTime);

        // Choice 2
        PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag");
        wl.acquire();
        wl.release();
    }
});
}

也获得了许可

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

仍显示例外情况

   01-14 16:06:00.875: E/AndroidRuntime(9317): FATAL EXCEPTION: main
   01-14 16:06:00.875: E/AndroidRuntime(9317): java.lang.SecurityException: Neither user 10079  nor current process has android.permission.DEVICE_POWER.
   01-14 16:06:00.875: E/AndroidRuntime(9317):  at android.os.Parcel.readException(Parcel.java:1322)
   01-14 16:06:00.875: E/AndroidRuntime(9317):  at android.os.Parcel.readException(Parcel.java:1276)
  01-14 16:06:00.875: E/AndroidRuntime(9317):   at android.os.IPowerManager$Stub$Proxy.goToSleep(IPowerManager.java:341)
  01-14 16:06:00.875: E/AndroidRuntime(9317):   at android.os.PowerManager.goToSleep(PowerManager.java:464)

2 个答案:

答案 0 :(得分:2)

您错过了DEVICE_POWER权限。

编辑: 显然,只允许系统应用程序使用此权限,因此您几乎被卡住了。

答案 1 :(得分:0)

将以下权限添加到你的清单:

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