import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
public class MainActivity extends Activity {
WakeLock wakeLock;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
acquireWakeLock();
}
@Override
protected void onDestroy() {
releaseWakeLock();
super.onDestroy();
}
private void acquireWakeLock() {
if (wakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyTag");
wakeLock.acquire();
}
}
private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock = null;
}
}
}
AndroidManifest中加上权限:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DEVICE_POWER" />
eclipse中会报错:
Permission is only granted to system apps
只要clean一下就好了。
关于
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyTag");
中的Flag,API中解释如下: