Android home键监听事件。

第一种:

@Override  
public void onAttachedToWindow() {  
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);  
    super.onAttachedToWindow();  
}

android4.0.1版本以后,用这种方法监听home事件,会报如下错误:

     java.lang.IllegalArgumentException: Window type can not be changed after the window is added。

所以这种方法不是通用的。

第二种:

  监听ACTION_CLOSE_SYSTEM_DIALOGS系统广播。

MainActivity.java:


public class MainActivity extends Activity {

	private InnerRecevier receiver;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
                //动态注册ACTION_CLOSE_SYSTEM_DIALOGS系统广播
                receiver = new InnerRecevier();
		IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		registerReceiver(receiver, homeFilter);
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
                //取消注册
                unregisterReceiver(receiver);
		super.onDestroy();
	}
}

InnerRecevier.java


class InnerRecevier extends BroadcastReceiver {
	final String SYSTEM_DIALOG_REASON_KEY = "reason";
	final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
	final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
	final String SYSTEM_DIALOG_REASON_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_DIALOG_REASON_KEY);
			Log.v("TAG", "onReceive-----------------");
			Toast.makeText(context, "onReceive", Toast.LENGTH_SHORT).show();
			/* 下面的启动Activity无效。貌似这样监听home事件,只能简单的打Log和Toast显示。连Dialog都显示不出来,不知为何,待日后发现。
			Intent intent1 = new Intent(context, MainActivity.class);
			context.startActivity(intent1);
			*/
		}
	}
}


你可能感兴趣的:(Android home键监听事件。)