Simulate the HOME key function in Android

Source: Internet
Author: User

Make a method similar to pressing the return key on QQ and does not destroy the Activity (that is, do not call the Activity. finish (), the system does not call onDestroy), but is similar to pressing the Home Key to make the Activity similar to "paused" (that is, only onPause and onDestroy are called ).

The Code is as follows:

 


[Java] public boolean onKeyDown (int keyCode, KeyEvent event ){
If (keyCode = KeyEvent. KEYCODE_BACK ){
Intent intent = new Intent (Intent. ACTION_MAIN );
Intent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); // note
Intent. addCategory (Intent. CATEGORY_HOME );
This. startActivity (intent );
Return true;
}
Return super. onKeyDown (keyCode, event );
}
Public boolean onKeyDown (int keyCode, KeyEvent event ){
If (keyCode = KeyEvent. KEYCODE_BACK ){
Intent intent = new Intent (Intent. ACTION_MAIN );
Intent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); // note
Intent. addCategory (Intent. CATEGORY_HOME );
This. startActivity (intent );
Return true;
}
Return super. onKeyDown (keyCode, event );
}

 

 

Pay special attention to intent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); this sentence must be added because the launchMode of the Activity is executed in standard by default, if this tag is not added, a new Activity is created and placed in the same Task as the current Activity. The FLAG_ACTIVITY_NEW_TASK description FLAG_ACTIVITY_NEW_TASK mark is as follows:

 


When the Intent object passed to startActivity () contains the FLAG_ACTIVITY_NEW_TASK tag, the system searches for different tasks for the activity to be started. If the affinity attribute of the activity to be started is different from that of all current tasks, the system creates a new task with the affinity attribute, and press the activity to be started into the new task stack; otherwise, press the activity into the stack with the same affinity attribute.

 

From Peking University-Google Android lab

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.