Android如何从BroadcastReceiver了解屏幕锁定的状态

时间:2012-10-08 14:10:16

标签: android broadcastreceiver

我正在为来电开发自定义用户界面。我差不多完成了这个,但现在我只想在屏幕打开且用户有来电时加载我的自定义UI活动。我正在BroadcastReceiver(android.intent.action.PHONE_STATE)做所有这些事情。因此可以从BrodcastReceiver获取屏幕ON / OFF的状态。

我试图遵循示例http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/但是从BroadcastReceiver注册接收器会产生编译时错误。

请建议我。

public class MyPhoneReceiver extends BroadcastReceiver {

     @Override
     public void onReceive(Context context, Intent intent) {


          IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
          filter.addAction(Intent.ACTION_SCREEN_OFF);
          BroadcastReceiver mReceiver = new MyScreenReceiver();
          registerReceiver(mReceiver, filter); //this gives error "The method registerReceiver(BroadcastReceiver, IntentFilter) is undefined for the type MyPhoneReceiver"


     }
}

的Manifest.xml

<receiver android:name="MyPhoneReceiver" >
     <intent-filter>
          <action android:name="android.intent.action.PHONE_STATE"/>
     </intent-filter>
</receiver>

由于

2 个答案:

答案 0 :(得分:1)

registerReceiver()是Context的一种方法,因此你应该调用context.registerReceiver(mReceiver, filter);

但你可以做到以下几点:

public class MyPhoneReceiver extends BroadcastReceiver {

     @Override
     public void onReceive(Context context, Intent intent) {

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if(pm.isScreenOn())
        {
            // load your UI
        }

     }
}

答案 1 :(得分:0)

以下是您的问题的解决方案..

public static boolean wasScreenOn = true;

@Override
public void onReceive(Context context, Intent intent) {
   if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        // DO WHATEVER YOU NEED TO DO HERE
        wasScreenOn = false;
    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        // AND DO WHATEVER YOU NEED TO DO HERE
        wasScreenOn = true;
    }

}