android 退出机制
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的退出机制的总结.
在以后的教程中,我们将一步步实现这样的效果.