【转】Android退到后台与切到前台

转载自:Android退到后台与切到前台

最近开发了一款TV版app,主要功能是视频通话,所以要求机顶盒是一开机,就要把app打开,因为时刻有别人打过来。然后点击返回按钮,需要把app切到后台,但是app仍需要存活,需要收到消息。所以这里就设计到了app退到后台与切到前台的功能。

app退到后台

1.一般情况下,是启动Home页就可以实现这个功能,代码如下

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);

这里需要注意的是,如果Launcher和Home不是同一个,那就不能这么用。比如说华数机顶盒Launcher,启动第三方app都是从这里打开的。然后这里如果执行了上述代码,启动了Home,那就跳转到了Android系统的Home,与退到后台的效果有所出入了。

2.执行Activity#moveTaskToBack()

moveTaskToBack(false);

这里也需要注意,传入的参数(boolean nonRoot)

/**
* Move the task containing this activity to the back of the activity
* stack. The activity's order within the task is unchanged.
*
* @param nonRoot If false then this only works if the activity is the root
* of a task; if true it will work for any activity in
* a task.
*
* @return If the task was moved (or it was already at the
* back) true is returned, else false.
*/
public boolean moveTaskToBack(boolean nonRoot) {}

根据源码注释可以知道,nonRoot=false时,只有当当前Activity为root activity根Activity时才会把当前task退回到后台。
notRoot=true时,不管当前是否是root activity都会把当前task退回到后台

app切到前台

1.使用Intent启动需要切到前台的Activity

Intent intent = new Intent(this, MainActivity.class);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setAction(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
startActivity(intent);

这里的MainActivity.class就是需要启动的Activity,用这个方法,当启动了其他app时,可能会失效。

2.通过ActivityMananger把task切到前台

ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
am.moveTaskToFront(getTaskId(), ActivityManager.MOVE_TASK_WITH_HOME);

发表评论