切换背景/前景模式

时间:2017-07-10 17:17:56

标签: java android android-intent

我试图这样做,以便当您按下电源按钮关闭Android时,我的应用程序进入后台模式。当您按下电源按钮打开Android时,我的应用程序应该进入前台模式。

我得到的错误是:

  

java.lang.RuntimeException:接收广播Intent时出错{   act = android.intent.action.SCREEN_ON flg = 0x50000010}

错误来自FLAG_ACTIVITY_CLEAR_TOP

的意图

这是MainActivity:

public class MainActivity extends AppCompatActivity {

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

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

            moveTaskToBack(true);
        }
    }

这是BroadcastReceiver:

public class ScreenReceiver extends BroadcastReceiver {

    MainActivity mainAct;
    Context ctx;
    public ScreenReceiver(MainActivity act, Context con) {
        mainAct = act;
        ctx = con;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            mainAct.moveTaskToBack(true);
            System.out.println("OFF");
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            Intent i = new Intent(ctx, ScreenReceiver.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            mainAct.startActivity(i);
            System.out.println("ON");
        }
    }

}

我使用以下教程中的代码:

https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/

1 个答案:

答案 0 :(得分:0)

错误是将ScreenReceiver.class而不是MainActivity.class传递给intent。这是更正后的版本:

public class ScreenReceiver extends BroadcastReceiver {

    MainActivity mainAct;
    Context ctx;
    public ScreenReceiver(MainActivity act, Context con) {
        mainAct = act;
        ctx = con;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            mainAct.moveTaskToBack(true);
            System.out.println("OFF");
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            Intent i = new Intent(ctx, MainActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            mainAct.startActivity(i);
            System.out.println("ON");
        }
    }

}