Android监听是否点击了home键或者锁屏键

不废话了,直接上代码:

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

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");
            }
        }
    };
}

你可能感兴趣的:(home键,锁屏键)