在SCREEN_OFF意图触发时调用活动(生命周期)的奇怪行为

时间:2013-07-04 18:02:01

标签: android android-intent

我正在开发幻灯片功能,此停止和重新启动会在幻灯片流程中产生问题,我们可以更改它吗?

生命周期记录方法

07-04 22:47:27.944: D/ReceiverActivity(7365): Activity Life cycle - onStart called
07-04 22:47:27.944: D/ReceiverActivity(7365): Activity Life cycle - onResume called
07-04 22:47:28.467: D/ReceiverActivity(7365): Activity Life cycle - onStop called
07-04 22:47:29.139: D/ReceiverActivity(7365): Activity Life cycle - onRestart called
07-04 22:47:29.139: D/ReceiverActivity(7365): Activity Life cycle - onStart called
07-04 22:47:29.139: D/ReceiverActivity(7365): Activity Life cycle - onResume called

这是我的应用代码片段

@Override
public void onReceive(final Context context, final Intent intent) {
    if(action.equals(Intent.ACTION_SCREEN_OFF)) {
        Intent ri = new Intent(context, ReceiverActivity.class);
            ri.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(ri);
    }
}


public class ReceiverActivity extends Activity
{
    StringBuilder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        // Turn on the screen unless we are being launched from the AlarmAlert
        // subclass as a result of the screen turning off.
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.launcher_layout);
        builder = new StringBuilder();
        builder.append("onCreate called.");
        Log.e("ReceiverActivity", "String : " + builder.toString());
    }

    @Override
    protected void onStart() {
        Log.d("ReceiverActivity","Activity Life cycle - onStart called");
        super.onStart();
        builder.append("\nonStart called.");
    }

    @Override
    protected void onResume() {
        Log.d("ReceiverActivity","Activity Life cycle - onResume called");
        super.onResume();
        builder.append("\nonResume called.");
        Log.e("ReceiverActivity", "String : " + builder.toString());
        ((TextView) findViewById(R.id.textView1)).setText(builder.toString());
    }
    @Override
    protected void onRestart() {
        Log.d("ReceiverActivity","Activity Life cycle - onRestart called");
        super.onRestart();
    }
    @Override
    protected void onStop() {
        Log.d("ReceiverActivity","Activity Life cycle - onStop called");
        super.onStop();
    }
}

提前致谢

1 个答案:

答案 0 :(得分:0)

在我看来,你需要知道在调用onResume时屏幕是否实际开启或关闭,以确定你应该如何处理事件。你想检查一下:

  • 您的活动位于前台。
  • 屏幕已开启。

Getting if Screen ON/OFF and if Application is in Background/Foreground给出了如何做到这两点的明确答案。