之前做FM时用到了一键退出整个应用程序的功能,通过查找和实践,现在在这里总结下如下解决办法.
首先编写一个工具类:AppClose.java
package com.xxxx.fm;
import android.app.Activity;
import android.app.Application;
import java.util.LinkedList;
import java.util.List;
public class AppClose extends Application {
private List<Activity> mList = new LinkedList<Activity>();
private static AppClose instance;
private AppClose() {
}
public synchronized static AppClose getInstance() {
if (null == instance) {
instance = new AppClose();
}
return instance;
}
public void addActivity(Activity activity) {
mList.add(activity);
}
public void exit() {
try {
for (Activity activity : mList) {
if (activity != null)
activity.finish();
}
mList = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
System.gc();
}
}
2.在activity的onCreate方法中添加:
AppClose.getInstance().addActivity(this);
3.在程序需要退出的地方调用:
AppClose.getInstance().exit();
最好不要忘记在AndroidManifest.xml文件中给application添加属性android:name=".AppClose"。