android sdk 退出机制的钻研 有多种,
办法一、用 list 保留 activity 实例,而后逐个干掉
上代码:
import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.content.DialogInterface; import android.content.Intent; public class SysApplication extends Application {
private List<Activity> mList = new LinkedList<Activity>();
private static SysApplication instance;
private SysApplication() {}
public synchronized static SysApplication getInstance() {if (null == instance) {instance = new SysApplication();
}
return instance;
}
// add Activity public void addActivity(Activity activity) {mList.add(activity);
}
public void exit() {
try {for (Activity activity : mList) {if (activity != null)
activity.finish();}
} catch (Exception e) {e.printStackTrace();
} finally {System.exit(0);
}
}
@Override
public void onLowMemory() {super.onLowMemory();
System.gc();}
}
在每个 Activity 的 onCreate 办法中增加相似代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SysApplication.getInstance().addActivity(this);
} public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SysApplication.getInstance().addActivity(this);
}
在须要退出程序的时候,调用:
SysApplication.getInstance().exit();
SysApplication.getInstance().exit();
简而言之,通过单例模式把每个 Activity 的援用增加到一个全局链表中,每次退出程序调用 System.exit(0) 时,先调用链表中 Activity 的 finish 办法
办法二、应用播送
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
manager.killBackgroundProcesses(package);
不行
android.os.Process.killProcess(android.os.Process.myPid());
也不行
manager.restartPackage(package);
还是不行
Intent MyIntent = new Intent(Intent.ACTION_MAIN);
MyIntent.addCategory(Intent.CATEGORY_HOME);
startActivity(MyIntent);
finish();
这个只是退回到桌面,如果关上多个 Activity 敞开从新关上也会有问题,还是还是不行
看到有说播送机制,发现是个好东东,能彻底解决这个问题,废话不说看代码:
public abstract class EnterActivity extends BaseActivity {
…
// 写一个播送的外部类,当收到动作时,完结 activity private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {unregisterReceiver(this); // 这句话必须要写要不会报错,不写尽管能敞开,会报一堆错 ((Activity) context).finish();}
};
@Override
public void onResume() {super.onResume();
// 在以后的 activity 中注册播送 IntentFilter filter = new IntentFilter();
filter.addAction(Attribute.PAGENAME);
registerReceiver(this.broadcastReceiver, filter); // 注册 }
/** * 敞开
*/ public void close() {Intent intent = new Intent();
intent.setAction(Attribute.PAGENAME); // 阐明动作 sendBroadcast(intent);// 该函数用于发送播送 finish();}
…
}
这就是 我对 android 中的 activity 的退出机制的总结.
在当前的教程中,咱们将一步步实现这样的成果.
参考:
http://www.developcls.com