为什么这个BroadcastReceiver没有工作?

时间:2013-09-01 16:54:29

标签: java android

我想制作一个BroadcastReceiver,以便在屏幕关闭时收到通知,然后我再次启用它,但它什么都不做,问题是什么?

public class SplashScreen extends SherlockActivity {
PowerManager.WakeLock mWakeLock;

BroadcastReceiver rec = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            WakeLock screenLock = ((PowerManager) getSystemService(POWER_SERVICE))
                    .newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                            | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
            screenLock.acquire();

        }

    }
};

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

    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    registerReceiver(rec, filter);
}

1 个答案:

答案 0 :(得分:0)

移动你的

BroadcastReceiver rec = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            WakeLock screenLock = ((PowerManager) getSystemService(POWER_SERVICE))
                    .newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                            | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
            screenLock.acquire();

        }

    }
};

在你的oncreate下

public class SplashScreen extends SherlockActivity {
PowerManager.WakeLock mWakeLock;

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

BroadcastReceiver rec = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            WakeLock screenLock = ((PowerManager) getSystemService(POWER_SERVICE))
                    .newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                            | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
            screenLock.acquire();

        }

    }
};
        registerReceiver(rec, new IntentFilter("package.name.xx"));
        pi = PendingIntent.getBroadcast(this, 0, new Intent(
                "package.name.xx"), 0);
}