用一个List集合存储存活的acitivity,我们把list作为application成员
写一个MyApp类,作为程序启动的application
public class MyApp extends Application{
private List<Activity>activities = new ArrayList<Activity>()
public List<Activity>getActivities(){
return activities
}
}
BaseActivity代码如下
class BaseActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
((MyApp)getApplication()).getActivities().add(this)
}
@Override
protected void onDestroy() {
super.onDestroy()
((MyApp)getApplication()).getActivities().remove(this)
}
}
以后工程里的所有Activity都继承于BaseActivity即可
最后是MainAcitivty的代码,在onkeydown方法里遍历list集合,调用每个activity的finish方法即可
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_two)
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
List<Activity>activities = ((MyApp)getApplication()).getActivities()
for(Activity activity:activities){
activity.finish()
}
return super.onKeyDown(keyCode, event)
}
}
监听返回键
public boolean onKeyDown(int keyCode, KeyEvent event) {if ((keyCode == KeyEvent.KEYCODE_BACK)) //表示按的是返回键
{
System.exit(0)//退出进程关闭app,或者可以写个工具类
//ActivityUtils.getInstance().addActivity(this)
//还有就是登录页面跳转的时候finish登录页面的activity
return false
}else {
return super.onKeyDown(keyCode, event)
} public class ActivityUtils{
private ActivityUtils() {
}
private static AtyContainer instance = new AtyContainer()
private static List<Activity> activitys = new ArrayList<Activity>()
public static ActivityUtils getInstance() {
return instance
}
public void addActivity(Activity activity) {
activityStack.add(activity)
}
public void removeActivity(Activity activity) {
activityStack.remove(activity)
}
/**
* 结束所有Activity
*/
public void finishAllActivity() {
for (int i = 0, size = activityStack.size() i < size i++) {
if ( != activityStack.get(i)) {
activityStack.get(i).finish()
}
}
activityStack.clear()
}
} public abstract class BaseActivity extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
// 添加Activity到堆栈
ActivityUtils.getInstance().addActivity(this)
}
protected void onDestroy() {
super.onDestroy()
// 结束Activity&从栈中移除该Activity
ActivityUtils.getInstance().removeActivity(this)
}
}
如果它没有后台服务的话,一般退出就是退出了;但对于有后台服务的app来说,没有暂停这回事,要么某些和前台有关的进程被关闭了,要么都留在后台了。一个app刚安装完没有符合它自启条件,比如开机,网络环境,其他app的广播(阿里连裆裤,百度航母群,企鹅一家亲)的时候是不会自启的。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)