Android app background running instructions, android background
- 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:
- Public boolean onKeyDown (int keyCode, KeyEvent event ){
- PackageManager pm = getPackageManager ();
- ResolveInfo homeInfo =
- Pm. resolveActivity (new Intent (Intent. ACTION_MAIN). addCategory (Intent. CATEGORY_HOME), 0 );
- If (keyCode = KeyEvent. KEYCODE_BACK ){
- ActivityInfo ai = homeInfo. activityInfo;
- Intent startIntent = new Intent (Intent. ACTION_MAIN );
- StartIntent. addCategory (Intent. CATEGORY_LAUNCHER );
- StartIntent. setComponent (new ComponentName (ai. packageName, ai. name ));
- StartActivitySafely (startIntent );
- Return true;
- } Else
- Return super. onKeyDown (keyCode, event );
- }
- Private void startActivitySafely (Intent intent ){
- Intent. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK );
- Try {
- StartActivity (intent );
- } Catch (ActivityNotFoundException e ){
- Toast. makeText (this, "null ",
- Toast. LENGTH_SHORT). show ();
- } Catch (SecurityException e ){
- Toast. makeText (this, "null ",
- Toast. LENGTH_SHORT). show ();
- }
- }
- The article is reposted on the Internet. Thanks to the original author for his selfless sharing.