package
com.exit;
import
java.lang.ref.SoftReference;
import
java.util.HashMap;
import
java.util.Iterator;
import
java.util.Map.Entry;
import
android.app.Activity;
import
android.content.Context;
import
android.content.Intent;
public
class
ActivityManager
{
private
Context context;
private
static
ActivityManager activityManager;
public
static
ActivityManager getActivityManager(Context context)
{
if
(activityManager ==
null
)
{
activityManager =
new
ActivityManager(context);
}
return
activityManager;
}
private
ActivityManager(Context context)
{
this
.context = context;
}
/**
* task map,用于记录activity栈,方便退出程序(这里为了不影响系统回收activity,所以用软引用)
*/
private
final
HashMap<String, SoftReference<Activity>> taskMap =
new
HashMap<String, SoftReference<Activity>>();
/**
* 往应用task map加入activity
*/
public
final
void
putActivity(Activity atv)
{
taskMap.put(atv.toString(),
new
SoftReference<Activity>(atv));
}
/**
* 往应用task map加入activity
*/
public
final
void
removeActivity(Activity atv) {
taskMap.remove(atv.toString());
}
/**
* 清除应用的task栈,如果程序正常运行这会导致应用退回到桌面
*/
public
final
void
exit()
{
for
(Iterator<Entry<String, SoftReference<Activity>>> iterator = taskMap.entrySet().iterator(); iterator.hasNext();) {
SoftReference<Activity> activityReference = iterator.next().getValue();
Activity activity = activityReference.get();
if
(activity !=
null
)
{
activity.finish();
}
}
taskMap.clear();
}
}
2、创建自己的根activity,重写onCreate与onDestory
package
com.exit;
import
android.app.Activity;
import
android.os.Bundle;
public
class
BaseActivity
extends
Activity {
private
ActivityManager manager = ActivityManager.getActivityManager(
this
);
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
manager.putActivity(
this
);
}
@Override
protected
void
onDestroy() {
super
.onDestroy();
manager.removeActivity(
this
);
}
public
void
exit(){
manager.exit();
}
}
3、以后创建的activity都继承这个根activity就可以了,如下
package
com.exit.activitys;
import
android.content.Intent;
import
android.os.Bundle;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.TextView;
import
com.exit.BaseActivity;
import
com.exit.R;
public
class
ExitActivity
extends
BaseActivity
implements
OnClickListener{
private
Button start;
private
Button exit;
private
TextView tipTV;
@Override
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button)findViewById(R.id.start_new_activity);
exit = (Button)findViewById(R.id.exit_all_activity);
tipTV = (TextView)findViewById(R.id.tip_tv);
tipTV.setText(
"activity:"
+
this
.toString());
start.setOnClickListener(
this
);
exit.setOnClickListener(
this
);
}
@Override
public
void
onClick(View v) {
if
(v == start){
Intent intent =
new
Intent(
this
, ExitActivity.
class
);
startActivity(intent);
}
else
if
(v == exit){
exit();
}
}
}