首先要在AndroidManifest中加权限
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.DEVICE_POWER" />
import android.os.BatteryStats.Uid.Wakelock;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
由于 Class是Fragment ,所以用
getActivity()去获取<pre name="code" class="java">getActivity().getSystemService
public class DoovTimerFragment extends DeskClockFragment
mPowerManager = (PowerManager)getActivity().getSystemService(Context.POWER_SERVICE);
mWakelock= mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
screenOn=(Switch)v.findViewById(R.id.ScreenOn);
if(screenOn.isChecked())
{
mWakelock.acquire();
}
screenOn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(screenOn.isChecked())
{
mWakelock.acquire();
}else
{
mWakelock.release();
}
}
});