屏幕开/关检测

时间:2012-11-09 11:50:30

标签: android

这里我试图确定屏幕是否打开但是当按下电源锁定/解锁按钮时它似乎不起作用。应用程序没有错误,但if-else中的代码似乎没有效果。 的被修改 现在代码工作(感谢 Olgun )但媒体播放器播放并没有停止,每次打开/关闭屏幕都会创建新的媒体播放器对象(多次播放)。

SCBroadcaster.java

    public class SCBroadcaster extends BroadcastReceiver {
    PowerManager pm;
    MediaPlayer mp;
    public static boolean wasScreenOn = true;

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub
        mp = MediaPlayer.create(arg0, R.raw.gale);
        if (arg1.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                    mp.stop();
            mp.release();
            Toast.makeText(arg0, "oNONONO", Toast.LENGTH_LONG).show();

        } else if (arg1.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            mp.start();
        }

    }

}

MainActivity.java

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    BroadcastReceiver bre = new SCBroadcaster();
    registerReceiver(bre, filter);
}

protected void onPause() {
    super.onPause();
    if (SCBroadcaster.wasScreenOn) {
        System.out.println("SCREEN TURNED OFF");
    } else {

    }
}

protected void onResume() {
    super.onResume();
    if (!SCBroadcaster.wasScreenOn) {

    } else {

    }
}

}

4 个答案:

答案 0 :(得分:8)

使用ACTION_SCREEN的方法对我不起作用。经过一些不同的解决方案,这段代码终于解决了我的问题:

/**
 * Is the screen of the device on.
 * @param context the context
 * @return true when (at least one) screen is on
 */
public boolean isScreenOn(Context context) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
        boolean screenOn = false;
        for (Display display : dm.getDisplays()) {
            if (display.getState() != Display.STATE_OFF) {
                screenOn = true;
            }
        }
        return screenOn;
    } else {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        //noinspection deprecation
        return pm.isScreenOn();
    }
}

答案 1 :(得分:7)

Intent.ACTION_SCREEN_OFF和ACTION_SCREEN_ON检查上述广播注册。 here你可以找到一个很好的例子。

答案 2 :(得分:3)

您可以尝试在活动中添加此内容。

IntentFilter filter = new IntentFilter(); 
filter.addAction(Intent.ACTION_SCREEN_OFF); 
BroadcastReceiver mReceiver = new ScreenReceiver(); 
registerReceiver(mReceiver, filter); 

同样,您也可以添加ACTION_SCREEN_ON

答案 3 :(得分:0)

BroadcastReceiverService个事件的背景Intent.ACTION_SCREEN_ON中注册Intent.ACTION_SCREEN_OFF。它对我有用。