Android app background running instructions, android background

Source: Internet
Author: User

Android app background running instructions, android background

  1. Rewrite the event listening of the Return key so that the back key function is similar to the home key, so that the Acitivty will not be destroyed by the system when it is returned to the background. The Code is as follows:
  2. Public boolean onKeyDown (int keyCode, KeyEvent event ){
  3. PackageManager pm = getPackageManager ();
  4. ResolveInfo homeInfo =
  5. Pm. resolveActivity (new Intent (Intent. ACTION_MAIN). addCategory (Intent. CATEGORY_HOME), 0 );
  6. If (keyCode = KeyEvent. KEYCODE_BACK ){
  7. ActivityInfo ai = homeInfo. activityInfo;
  8. Intent startIntent = new Intent (Intent. ACTION_MAIN );
  9. StartIntent. addCategory (Intent. CATEGORY_LAUNCHER );
  10. StartIntent. setComponent (new ComponentName (ai. packageName, ai. name ));
  11. StartActivitySafely (startIntent );
  12. Return true;
  13. } Else
  14. Return super. onKeyDown (keyCode, event );
  15. }
  16. Private void startActivitySafely (Intent intent ){
  17. Intent. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK );
  18. Try {
  19. StartActivity (intent );
  20. } Catch (ActivityNotFoundException e ){
  21. Toast. makeText (this, "null ",
  22. Toast. LENGTH_SHORT). show ();
  23. } Catch (SecurityException e ){
  24. Toast. makeText (this, "null ",
  25. Toast. LENGTH_SHORT). show ();
  26. }
  27. }
  28. The article is reposted on the Internet. Thanks to the original author for his selfless sharing.

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.