android实现程序的后台运行

改写返回键事件监听,使得back键功能类似home键,让Acitivty退至后台时不被系统销毁,代码如下:
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();   
        }  
    }
文章转载自互联网,感谢原作者的无私分享。 

你可能感兴趣的:(android实现程序的后台运行)