解决方法
我使用了像timonvlad这样的broadcastReceiver,但是XML无法调用ACTION_SCREEN_ON和ACTION_SCREEN_OFF,所以我创建了一个服务.该服务必须在XML中注册然后我使用此代码
public class OnOffReceiver extends Service { @Override public IBinder onBind(Intent arg0) { // Todo Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent,int flags,int startId) { registerReceiver(new broadcastReceiver() { public void onReceive(Context context,Intent intent) { //This happens when the screen is switched off } },new IntentFilter(Intent.ACTION_SCREEN_OFF)); registerReceiver(new broadcastReceiver() { public void onReceive(Context context,Intent intent) { //This happens when the screen is turned on and screen lock deactivated } },new IntentFilter(Intent.ACTION_USER_PRESENT)); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); } }