从服务调用startActivity不允许关闭屏幕

时间:2014-12-29 13:52:58

标签: android android-activity android-service

Hello Stackoverflow用户,

我正在尝试使用以下代码为此条件if(intent.getAction().equals(Intent.ACTION_SCREEN_ON))打开新活动(该服务具有BroadcastReceiver)

    Intent intent = new Intent(context, OverlayActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

问题是当新活动打开时,屏幕超时设置不像以前那样工作,并且屏幕始终打开。活动中没有标记FLAG_KEEP_SCREEN_ON。 Activity只有空onCreate()方法。我无法弄清楚问题是什么。为什么屏幕超时(15秒)后屏幕没有关闭?当我在没有此活动的情况下运行服务时,它通常会禁用屏幕。

1 个答案:

答案 0 :(得分:0)

对于Intent.ACTION_SCREEN_OFF和Intent.ACTION_SCREEN_ON,你不能在Android Manifest中声明它们!

你可能会犯这个错误。

检查此代码 -

public class ScreenReceiver extends BroadcastReceiver {

    public static boolean wasScreenOn = true;

    @Override
    public void onReceive(final Context context, final 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;
        }
    }

}

和活动 -

public class ExampleActivity extends Activity {

    private BroadcastReceiver mReceiver = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // initialize receiver
        final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
        // your code
    }

    @Override
    protected void onPause() {
        // when the screen is about to turn off
        if (ScreenReceiver.wasScreenOn) {
            // this is the case when onPause() is called by the system due to a screen state change
            Log.e("MYAPP", "SCREEN TURNED OFF");
        } else {
            // this is when onPause() is called when the screen state has not changed
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // only when screen turns on
        if (!ScreenReceiver.wasScreenOn) {
            // this is when onResume() is called due to a screen state change
            Log.e("MYAPP", "SCREEN TURNED ON");
        } else {
            // this is when onResume() is called when the screen state has not changed
        }
    }

    @Override
    protected void onDestroy() {
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
        }
        super.onDestroy();
    }

}

这可能会解决您的问题。

干杯:)