Android監聽是否點擊了home鍵或者鎖屏鍵

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter filter = new IntentFilter();
        //鎖屏廣播,由系統發出
        filter.addAction(Intent.ACTION_SCREEN_ON);
        //鎖屏廣播,由系統發出
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        //點擊home鍵廣播,由系統發出
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(homeAndLockReceiver, filter);
    }

    /**
     * 監聽是否點擊了home鍵將客戶端推到後臺
     */
    private BroadcastReceiver homeAndLockReceiver = new BroadcastReceiver() {
        String SYSTEM_REASON = "reason";
        String SYSTEM_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                    //表示按了home鍵,程序到了後臺
                    Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_SHORT).show();
                }
            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
                //屏幕亮了
                Log.i("lock-", "--on");

            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                //屏幕黑了
                Log.i("lock-", "--off");
            }
        }
    };
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章